Static Service Management
Technical explanation of service implementation.
Last updated
Technical explanation of service implementation.
Last updated
One important challenge in the upgrade from Desktop to Web application is the handle of the static variables, in this scenario, the Desktop application only have one scope, if you execute multiple instances of the same application each one will have its own context, in Web application there are different scenarios.
For example, in Blazor WebAssembly deploy it will create one scope per tab or SignalR connection, so it won’t require any change given is a similar execution mode.
In Blazor Server we only have a server-client architecture so, It'll be the same server handling different connections, the scope of the static variables are global, so if you as a user open different tabs, they’ll share the same static variables and values, not per session/tab as expected. As we can see in the following diagram the life cycle of a static variable will persist during the whole server execution.
After some research of different approaches a StaticService is implemented, this service is global and will store the value of the static variable per session, handling by itself the session and the storage. It will give us the following methods:
Get which will return the value stored in the service for this static variable.
Set will set the value into the service for this static variable.
InitializeData, when we have a static property auto-implemented in the source code with a default value, we need to keep the value, but C# doesn’t allow non-auto-implemented properties to be initialized, so this method will set the corresponding value to the property in the first call on Get.
This service will involve changes on the conversion of the static variables that we’ll review in the following section.
Conversion Changes
This feature implies that we need changes in the converted code, principally on the getters and setters, each one will require to call the methods. One important decision we made during the design of this feature is to keep the code visible instead of using some attribute in order to increase the visibility and the maintainability of the converted code. Here we have a basic example with no initialization:
Winforms:
Blazor:
There is another example when an initialization is set on the static variable.
Winforms:
Blazor:
Service Setup
The StaticService requires some configuration in the program of our new application, is necessary to add the Session, DistribuitedMemoryCache service, HttpContextAccessor and initialize the services as we can see in the following code:
These services are required to be provided to the StaticServices to handle the different sessions and identify which one is the current session that is being consulted.