Home > Software engineering >  Instantiate one object for all blazor pages in Blazor WebAssembly?
Instantiate one object for all blazor pages in Blazor WebAssembly?

Time:10-21

I have a blazor webassmbly app and I want to instantiate an object only once that can be shared between all the blazor pages on client side. What I want to do is to instantiate this object when the application starts, in Program.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 Program.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 Program.cs. But is null. The AccountService object is created as a scoped object before calling GetCurrentMethod() in Program.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.

CodePudding user response:

I simply instantiate the service provider in Program.cs file like this:
ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();

Try it like this:

var app = appBuilder.Build();

AccountService accountService =  app.Services.GetRequiredService<AccountService>();
 
... // do your thing here

await app.Run();

That way you use the same Service provider as later on in your program.

  • Related