Search code examples
dependency-injectionblazorprogram-entry-pointwebassembly

blazor wasm inject IJSRuntime in program.cs Main


in Blazor Webassembly, is it possible to inject IJSRuntime in program.cs, to Main method ?

Thank you


Solution

  • Yes, you can get it from the services container

    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");
        builder.Services.AddSingleton(new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
    
    
        var host = builder.Build();
    
        var jsRuntime = host.Services.GetRequiredService<IJSRuntime>(); // get the service from the DI container
        // do something like get the culture - that's what the MS example for that does
        var cultureName = await jsRuntime.InvokeAsync<string>("blazorCulture.get");
    
        await host.RunAsync();
    }