Dependency Injection in Blazor: Inject All the Things

Dependency Injection in Blazor Components Explained

Still spinning up HttpClient manually in your Blazor components like it’s 2005? It’s time to modernize your approach with Dependency Injection (DI) — a core feature in Blazor that can streamline your code and supercharge testability.

Blazor, both Server and WebAssembly, embraces DI out of the box. Services are registered in Program.cs using scoped, singleton, or transient lifetimes. Injecting them is as easy as using the @inject directive in your .razor files or the [Inject] attribute in your code-behind.

Let’s say you have a WeatherService:

public class WeatherService
{
    private readonly HttpClient _httpClient;

    public WeatherService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<WeatherForecast[]> GetForecastAsync()
    {
        return await _httpClient.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
    }
}

Register it in Program.cs:

builder.Services.AddScoped<WeatherService>();

Then inject and use it in a Razor component:

@inject WeatherService WeatherService

@code {
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await WeatherService.GetForecastAsync();
    }
}

Notice how we didn’t instantiate HttpClient manually. In Blazor WebAssembly, HttpClient is pre-configured to work with the base address of the app. In Blazor Server, you typically register it with AddHttpClient<WeatherService>() to enable pooling and DNS refresh.

Using DI avoids tight coupling, facilitates unit testing (mock those dependencies!), and leads to cleaner, more maintainable code. Stop littering your components with new instances. Let the framework do the wiring.

Want to go deeper with Blazor? Experiment with different service lifetimes and scopes to see how they impact your app’s behavior and performance!

Leave a Reply

Your email address will not be published. Required fields are marked *