Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Blazor scoped service using async method before components are initialized

I have a scoped service:

services.AddScoped<UserSettingsService>();

I want to call async method on the service (load data from DB) before child components are initialized (before ComponentBase.OnInitialized();)

Where is the best place to call UserSettingsService.LoadAsync();?

I have tried to do it in App component in OnInitializedAsync(), but it seems too late, because my childcomponents has been initialized before the UserSettingsService:

app.razor.cs:

public partial class App {
  [Inject] UserSettingsService UserSettingsService {get; set;}
  [Inject] AuthenticationStateService AuthenticationStateService {get; set;}
 
  public override async Task OnInitializedAsync() {
     string userName = (await AuthenticationStateService.GetAuthenticationState()).User.Identity.Name;
     await UserSettingsService.LoadAsync(userName );
     await base.OnInitializedAsync();
  }
}
like image 839
Liero Avatar asked Dec 06 '25 03:12

Liero


1 Answers

As far as I know, SetparametersAsync should do the trick.

The image is very clear about the blazor component lifecycle: https://knowledgebasehavit.files.wordpress.com/2019/11/blazor-component-lifecycle-diagram.png

like image 67
Mario_P Avatar answered Dec 07 '25 15:12

Mario_P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!