Advertisement
Intermediate .NET, Blazor (Server & WebAssembly)

How does dependency injection work in Blazor components, and what's the difference between @inject and constructor injection?

Short answer

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…

Save .NET mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • Why can't Blazor components use constructor injection like typical services?
  • How does service lifetime (scoped vs singleton) differ in meaning between Blazor Server and WebAssembly?
Related topics