-
Notifications
You must be signed in to change notification settings - Fork 0
Sessions.Binding.SessionBindingService
BlazorSessionProvider.Sessions.Binding.SessionBindingService is a scoped service that allows binding one or more session values to a class. It provides a two-way binding system between an object’s properties and session keys, using attributes to map properties and INotifyPropertyChanged to maintain automatic synchronization.
In short: it’s a connection between a POCO object and the user’s session.
SessionBinder is the base class that allows derived classes to have properties bound to the session using [BindToKey].
Each property you want to synchronize with the session must be marked with BindToKey.
The constructor of your derived class should also call the base class constructor to initialize the mapping of each property.
Important
It is optional to give a key name to theBindToKeyattribute. If omitted, the session key will be the property name.
public class MyBinder : SessionBinder
{
[BindToKey("variable1")]
public int Var1
{
get => GetValue<int>();
set => SetValue(value);
}
// In this case, the session key is "UserName"
[BindToKey]
public string UserName
{
get => GetValue<string>();
set => SetValue(value);
}
// Bind as many properties as you want...
public MyBinder() : base() // <- "base()" to initialize the map
{
...
}
}The GetValue and SetValue methods are placed on the get and set of each property, respectively, so that the binding service correctly retrieves and stores the values in the session.
...
builder.Services.AddSessionProvider(config => { ... });
builder.Services.AddBindingService<MyBinder>();
...@page "/example"
@inject SessionBindingService<MyBinder> _binding
...Once the service is injected, the object must be initialized from the session:
public async Task MyMethod()
{
MyBinder binder = await _binding.InitializeBindedAsync();
binder.UserName = "Jhon Doe";
}This will:
- Create the instance of
MyBinder. - Check all properties with
[BindToKey]. - Load the values from the session (if they exist).
- Subscribe to the
PropertyChangedevent to keep the session automatically synchronized. Any changes to the properties update the session.
If you want to intercept changes or do something additional when a property changes, you can subscribe to PropertyChanged:
binder.PropertyChanged += (sender, e) => {
Console.WriteLine($"Propiedad {e.PropertyName} cambió");
};Made with ❤️ by Oscar D. Soto