0
votes

In my project I'd like to get all configuration information locally when the project starts. I created a ConfigurationManager service with HttpClient injected into it. On Blazor components there are lifecycle events such as OnInitializedAsync that get called when the component is created.

protected override async Task OnInitializedAsync()
{
    await ...
}

Is there something equivalent for services?

Program.cs contains the following

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
    builder.Services.AddScoped<StateManager>();
    await builder.Build().RunAsync();
}
1
Can you provide more of your code to get a better understanding? It would be helpful to see the ConfigurationManager service with HttpClient injected into it. - xcopy
Please specify what the problem is. We need details on what's not working and the code to reproduce it. - JHBonarius

1 Answers

0
votes

Adding state manager with builder.Servuces.AddScoped<StateManager>() doesn't give a reference to the service so it's not possible to call non-static methods, so I tried this

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");

    var http = new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) };
    builder.Services.AddScoped(sp => http);

    var state = new StateManager(http);
    builder.Services.AddScoped(sp => state);
    await state.LoadAsync();
    await builder.Build().RunAsync();
}