Instantiate one object for all blazor pages in Blazor WebAssembly?
I have a blazor webassmbly app and I want to instantiate an object only once that can be shared between all the blazor pages. What I want to do is to instantiate this object when the application starts, in StartUp.cs and then inject that object in all pages to use it. What I did was to create this class :
public class AccountService
{
HttpCaller _httpCaller;
AuthenticationStateProvider _provider;
public AccountViewModel _currentAccount;
public AccountService(HttpCaller caller, AuthenticationStateProvider provider)
{
_httpCaller = caller;
_provider = provider;
}
public async Task<OperationResult<AccountViewModel>> GetCurrentAccount()
{
if (await UserIsAuthenticated())
{
return await _httpCaller.HttpCall<bool, AccountViewModel>(API.GetCurrentAccount, true, true);
}
return NotAuthenticated<AccountViewModel>();
}
}
I call GetCurrentAccount() method and associate the result to _currentAccount property in in StartUp.cs class :
AccountService accountService = serviceProvider.GetRequiredService<AccountService>();
var result = await accountService.GetCurrentAccount();
if (result.IsSucces)
{
accountService._currentAccount = result.Result;
};
Then I inject AccountService object in a blazor page and my expectation is that _currentAccount property should contain the AccountViewModel object associated in StartUp.cs. But is null. The AccountService object is created as a scoped object before calling GetCurrentMethod() in StartUp.cs class:
builder.Services.AddScoped<AccountService>();
From my knowledge a scoped object should exist until the app is reloaded, there is no reloading but the _currentAccount property is still null.