🎓 All Courses | 📚 Blazor WASM Syllabus
Stickipedia University
📋 Study this course on TaskLoco

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.

Registering Services

// Program.cs
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddSingleton<AppState>();
builder.Services.AddHttpClient();

Service Lifetimes

  • Singleton — one instance for the entire app lifetime
  • Scoped — one instance per user session (in WASM: per browser tab)
  • Transient — new instance every time it is requested

Injecting into a Component

@inject IProductService ProductService
@inject NavigationManager Nav

@code {
    protected override async Task OnInitializedAsync()
    {
        var products = await ProductService.GetAllAsync();
    }
}

Constructor Injection in Services

public class ProductService
{
    private readonly HttpClient _http;
    public ProductService(HttpClient http) { _http = http; }
}

YouTube • Top 10
Blazor WASM: Dependency Injection
Tap to Watch ›
📸
Google Images • Top 10
Blazor WASM: Dependency Injection
Tap to View ›

Reference:

Wikipedia: Dependency Injection

image for linkhttps://en.wikipedia.org/wiki/Dependency_injection

📚 Blazor WASM — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT