static void

Blazor Dependency Injection

In Program.cs (you can use Autofac)

In WASM, everything Scoped is essentially Singleton - the lifetime is as long as the browser is open.

Registration (Program.cs)

NB: ILogger, IJSRuntime and NavigationManager are automatically registered by Blazor.

See HttpClient for registration of HttpClient and HttpClientFactory.

builder.Services.AddScoped<IMyService, MyService>();
//keyed services in .net8
builder.Services.AddKeyedScoped<IScaleService, BigService>("Big");
builder.Services.AddKeyedScoped<IScaleService, SmallService>("Small");
var webAssemblyHost = builder.Build();

var myService = webAssemblyHost.Services.GetRequiredService<IMyService>();
//you can configure between Build and Run
myService.Init(builder.Configuration);
await webAssemblyHost.RunAsync();

Injecting into components

Blazor components can use the inject operator ...

@inject IHttpClientFactory ClientFactory
@inject IConfiguration Configuration
@inject IMyService MyService

...or an attributed property...

@code {
    [Inject]
    public IMyService MyService { getset; } = default!;

...with keyed services in .net8...

[Inject(Key = "key")]
public HttpClient Http { getset; } = default!;