Should I call IAsyncDisposable.DisposeAsync() in Program.cs using JS module?

580 Views Asked by At

I need to configure localization in Blazor WASM, .NET 6

According to the manual, I need to use JavaScript in the Program.cs file. Microsoft recommends connecting JavaScript code through JavaScript isolation in JavaScript modules. However, the code specified in the example is the Blazor component, and IAsyncDisposable.DisposeAsync() is called there

Do I need to call IAsyncDisposable.DisposeAsync() in Program.cs and if so, how to do it without resorting to creating the Program class and the Main method, but using a new version of the console program template?

1

There are 1 best solutions below

1
On

The question is very stupid on my part. I didn't see the most obvious solution.

You can just call the DisposeAsync() method manually when the object is no longer needed.

As a result, the code will look like this. The code is slightly different from the template, so part of the logic is placed in a separate class.

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.JSInterop;

using Store.Client;
using Store.Client.Engine;

using System.Globalization;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

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

var host = builder.Build();

var js = host.Services.GetRequiredService<IJSRuntime>();
var module = await js.InvokeAsync<IJSObjectReference>("import", "./js/scripts.js");

var culture = await module.InvokeAsync<string>("getCulture");

if (culture is not null)
{
    Culture.Current = new CultureInfo(culture);
}
else
{
    Culture.Current = Culture.Default;

    await module.InvokeVoidAsync("setCulture", Culture.Current.Name);
}
    
await module.DisposeAsync();

await host.RunAsync();