.NET › Blazor (Server & WebAssembly)
How does dependency injection work in Blazor components, and what's the difference between @inject and constructor injection?
IntermediateAnswer
Blazor components support DI via the @inject directive (syntactic sugar generating a property with [Inject] attribute) or explicit [Inject] properties, resolving services from the DI container when the component is instantiated -- components generally can't use constructor injection directly since the framework controls their instantiation, unlike typical .NET classes.
@inject IUserService UserService
@inject NavigationManager Navigation
@code {
protected override async Task OnInitializedAsync() {
var user = await UserService.GetCurrentUserAsync();
if (user == null) Navigation.NavigateTo("/login");
}
}Real-world example A shared authentication check pattern injects both a UserService and NavigationManager into every protected page component, redirecting unauthenticated users to a login page directly from OnInitializedAsync.