
Dependency Injection (DI) is a first-class citizen in Blazor. Register services in Program.cs and inject them into components using @inject or the [Inject] attribute.
// Program.cs
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddSingleton<AppState>();
builder.Services.AddHttpClient();@inject IProductService ProductService
@inject NavigationManager Nav
@code {
protected override async Task OnInitializedAsync()
{
var products = await ProductService.GetAllAsync();
}
}public class ProductService
{
private readonly HttpClient _http;
public ProductService(HttpClient http) { _http = http; }
}Reference:
TaskLoco™ — The Sticky Note GOAT