Instantiate one object for all blazor pages in Blazor WebAssembly?

Daniel Avadanei 41 Reputation points
2021-10-19T14:34:42.75+00:00

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.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,156 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,385 questions
{count} votes