I have a Blazor server application in which I have a service registered to maintain state as follows:
public class AppState
{
public bool IsAuthenticated { get; set; }
public string UserId { get; set; }
}
In program.cs
builder.Services.AddScoped<AppState>();
In Index.razor
in OnInitialized()
I set some value in AppState:
@inject AppState AppState
protected override void OnInitialized()
{
AppState.UserId = "logged in userid";
}
I inject this service in components to grab whatever is required from the scoped service.
However, if I do this in a DataService.cs (which is also scoped) and create an instance of ApplicationDbContext:
public class DataService
{
private IServiceScopeFactory _scopeFactory;
private AppState _appState;
public DataService(IServicesScopeFactory scopeFactory, AppState appState)
{
_scopeFactory = scopeFactory;
_appState = appState;
}
public async Task<List<Patient>> GetAllPatientsAsync()
{
List<Patient> patients = new List<Patient>();
using (var scope = _scopeFactory.CreateScope())
{
var context =
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
//access the ApplicationDbContext
}
return patients;
}
public class ApplicationDbContext : IdentityDbContext
{
public Guid _tenantId;
AppState _state;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options, ITenantProvider _tenantProvider, AppState appState)
: base(options)
{
_tenantId = _tenantProvider.GetTenantId();
_state = appState; //seems a new instance of AppState is provided
here...
}
It seems that AppState is reintialized (inside the newly created ApplicationDbContext) and I do not get the value of userId that I set in Index.razor. It appears to me that when I use ScopeFactory, to create a scope and call ApplicationDbContext from that scope, a new scoped instance of AppState is created.
What is the solution to this? I need the original AppState maintained.