Dependency injection (DI) is a fundamental principle in software design that promotes loose coupling, code re usability, and test ability.
Blazor's built-in DI container runs DI by controlling the generation and lifetime of objects and their dependencies.
Developers can register services with the DI container, defining their lifespan scopes (transient, scoped, or singleton), and then inject these services into components or other services as required. This approach decouples components from their dependencies, making the code more modular and easier to maintain and test.
Blazor uses the same DI system as ASP.NET Core, hence allowing developers to easily connect with current .NET services and libraries and providing a consistent development experience between client-side and server-side components.
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using YourBlazorApp;
using YourBlazorApp.Services;var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// Register a transient service
builder.Services.AddTransient<ITaskService, TaskService>();
// Register a scoped service
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
// Register a singleton service
builder.Services.AddSingleton<ILoggingService, LoggingService>();await builder.Build().RunAsync();
Transient
Every time a worker needs a specific tool (the service), a brand new one is taken from the store. Once the worker is done with it for that particular task, it's returned (or discarded, and a new one will be fetched next time).
A new instance of the service is created every time it's requested from the DI container.
Scoped
A single instance of the service is created once per scope. In Blazor Server, a scope typically aligns with a user's session or a single HTTP request. In Blazor WebAssembly, it generally means once per page load.
Singleton
Only one instance of the service is created for the entire lifetime of the application. This instance is created the first time it's requested.