Skip to content

Dependency Injection in Blazor

Configuring Services

Blazor supports dependency injection through the service container in Program.cs. Services can be registered with different lifetimes.

csharp
// Program.cs
builder.Services.AddSingleton<TimeService>();
builder.Services.AddScoped<DataService>();
builder.Services.AddTransient<LoggerService>();

Service Lifetimes

Singleton

  • Single instance for all users and components
csharp
builder.Services.AddSingleton<IMyService, MyService>();

Scoped

  • New instance for each circuit/user session
csharp
builder.Services.AddScoped<IDataService, DataService>();

Transient

  • New instance each time requested
csharp
builder.Services.AddTransient<ILoggerService, LoggerService>();

Injecting Services in Components

To use a service within a component, use the @inject directive:

razor
@inject TimeService Time
@inject IDataService DataService

<p>The time is: @Time.GetCurrentTime()</p>
<button @onclick="LoadData">Load Data</button>

@code {
    private async Task LoadData()
    {
        await DataService.LoadDataAsync();
    }
}

Constructor Injection

You can also inject services using constructor injection in component classes:

csharp
public class MyComponent : ComponentBase
{
    private readonly IDataService _dataService;
    private readonly ILogger<MyComponent> _logger;

    public MyComponent(IDataService dataService, ILogger<MyComponent> logger)
    {
        _dataService = dataService;
        _logger = logger;
    }
}

Creating Services

Example of a service class:

csharp
public interface ITimeService
{
    string GetCurrentTime();
}

public class TimeService : ITimeService
{
    public string GetCurrentTime()
    {
        return DateTime.Now.ToShortTimeString();
    }
}

HTTP Client Factory

Register and use HTTP clients:

csharp
// Program.cs
builder.Services.AddHttpClient();
builder.Services.AddHttpClient("api", client => 
{
    client.BaseAddress = new Uri("https://api.example.com");
});

// Component
@inject IHttpClientFactory ClientFactory

@code {
    private async Task FetchData()
    {
        var client = ClientFactory.CreateClient("api");
        var response = await client.GetAsync("data");
    }
}