Constructor Dependency Injection in Blazor Components’ partial classes
As of writing this article, till the ASP.NET Core 6.0 preview-2, Blazor components’ partial classes don’t support constructor dependency injection.
But we can easily overcome this limitation by using a small open-source Blazor library called TanvirArjel.Blazor as follows:
First, we have to install the TanvirArjel.Blazor NuGet package as follows:
PMC:
Install-Package TanvirArjel.Blazor
.NET CLI:
dotnet add package TanvirArjel.Blazor
Then for Blazor Server, in the ConfigureServices method of the Startup class:
using TanvirArjel.Blazor.DependencyInjection;
services.AddComponents();
For Blazor WebAssembly, in the Main method of Program class:
using TanvirArjel.Blazor.DependencyInjection;
builder.Services.AddComponents();
That’s it. Now you can inject the dependencies in your Blazor component partial classes constructor as follows:
public partial class FetchDataComponent
{
private readonly WeatherForecastService _forecastService;
public FetchDataComponent(WeatherForecastService forecastService)
{
_forecastService = forecastService;
} private WeatherForecast[] Forecasts { get; set; } protected override async Task OnInitializedAsync()
{
Forecasts = await _forecastService.GetForecastAsync(DateTime.Now);
}
}
Happy Software Development!