blazor wasm 在 program.cs Main 中注入 IJSRuntime

blazor wasm inject IJSRuntime in program.cs Main

在 Blazor Webassembly 中, 是否可以将 program.cs 中的 IJSRuntime 注入 Main 方法?

谢谢

是的,您可以从服务容器中获取它

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();
}