Dependency Injection is a technique for accessing services configured in a central location.
- Blazor has built-in support for dependency injection (DI).
- Users can use predefined services in their apps by directly injecting them in the components.
- Blazor apps can also define custom services and make them available via DI.
Blazor has a special base component called OwningComponentBase. For example, a component is created by the user by extending the OwningComponentBase will have special controls over injected services and ensure their proper disposal when a component is destroyed. Users can create custom services and use those services in the entire application. To do so, the custom services need to be added to the startup.cs (server side) and to program.cs (client-side Blazor) as either a singleton or scoped service.
[startup.cs]
public class Startup {
public void ConfigureServices(IServiceCollection services)
{
.....
.....
services.AddScoped<Custom_ServiceName>();
}
}
[program.cs]
public class Program
{
public static async Task Main(string[] args)
{
……
builder.Services.AddSingleton<Custom_Service_Name>();
}
}
For more information, please refer here.
Share with