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();
//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
@inject IConfiguration Configuration
@inject IMyService MyService
...or an attributed property...
@code {
[Inject]
public IMyService MyService { get; set; } = default!;
[Inject]
public IMyService MyService { get; set; } = default!;
...with keyed services in .net8...
[Inject(Key = "key")]
public HttpClient Http { get; set; } = default!;
public HttpClient Http { get; set; } = default!;