Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 41 ยท State and Dependency Injection

Dependency Injection in Blazor

Use dependency injection in Blazor components with @inject and [Inject], register services in Program.cs, inject into services, and build a tiny container to see how it works.

A component that creates its own helpers (new ProductRepository(), new HttpClient()) is hard to test, hard to change and impossible to share between pages. Dependency injection (DI) flips the arrangement: a component declares what it needs, and the framework supplies it. Blazor is built on the same DI container as the rest of ASP.NET Core, so everything you know about services, lifetimes and constructors applies, with a few component-specific twists.

In this lesson you register services, inject them into components in three ways, learn the places where the usual constructor injection does not apply, and watch a miniature container resolve a dependency graph. The Blazor syntax is real but read-only; the container you can run is a stand-in written in plain C# with reflection.

Registering services

Services are registered in Program.cs on builder.Services. A service is usually an interface plus an implementation:

C#
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddHttpClient<IWeatherClient, WeatherClient>();

The interface is the contract components code against; the implementation can be swapped in tests or per environment. Lifetimes (AddSingleton, AddScoped, AddTransient) decide how long an instance lives. They matter a lot in Blazor and have their own lesson: Service Lifetimes and Scopes.

Injecting into components

There are three ways to receive a service in a Razor component.

1. The @inject directive (the usual choice):

RAZOR
@page "/products"
@inject IProductService Products

<ul>
    @foreach (var p in products)
    {
        <li>@p.Name</li>
    }
</ul>

@code {
    private List<Product> products = [];

    protected override async Task OnInitializedAsync()
        => products = await Products.GetAllAsync();
}

@inject Type Name becomes a property named Name on the generated class, filled in before OnInitialized runs.

2. The [Inject] attribute, needed in code-behind files and base classes:

C#
public partial class Products : ComponentBase
{
    [Inject] private IProductService Service { get; set; } = default!;
}

The = default! quiets the nullable warning: the framework assigns the property after construction.

3. Constructor injection, which works in code-behind partial classes with a primary constructor (and always for services):

C#
public partial class Products(IProductService service) : ComponentBase { }

Property and directive injection come from the era when components had to have a parameterless constructor; they remain the most common style in Razor files.

Injecting into _Imports

If every component in a folder needs NavigationManager or a logger, write @inject once in _Imports.razor. It is visible to all components below, but use it sparingly: hidden dependencies make a component harder to read.

Services that depend on services

A service can ask for other services in its constructor. The container builds the whole dependency graph for you.

C#
public class OrderService(IProductService products, IClock clock, ILogger<OrderService> log) : IOrderService
{
    public Order Create(int productId)
    {
        var p = products.Find(productId);
        log.LogInformation("Order for {Name} at {Time}", p.Name, clock.Now);
        return new Order(p, clock.Now);
    }
}

Registering IOrderService is enough; its three dependencies are resolved recursively. If any of them is missing the container throws InvalidOperationException: Unable to resolve service for type ... at the first request for it.

What the container does

The container is not magic. It looks at a class's constructor, finds the parameter types, resolves each (recursively), then calls the constructor. The stand-in below does exactly that for registered types, so you can see the graph being built and the error you get for a missing registration.

C# A tiny DI container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The nested printing shows the order: OrderService is asked for, its dependencies are created first, then the service itself.

Component injection vs. constructor injection

Why do Razor components mostly use @inject rather than constructors? A component is instantiated by the renderer, not by you, and it may need services before parameters arrive. @inject is simply a convention that compiles to [Inject] properties. Both styles read from the same container, and both honor the lifetimes you registered.

A second difference: a component is not itself registered in the container. You cannot AddScoped<MyComponent>(). To get a component by DI-like behavior you use [Inject] properties on it.

Where DI does not reach

  • Static classes and static members cannot be injected. Pass the service as a parameter instead.
  • Components you create with new get nothing injected: the [Inject] properties stay null. Always let the framework create components, through markup or DynamicComponent.
  • Property injection of optional services: [Inject] with a nullable type still throws if the service is not registered; there is no "optional" mode. Use IServiceProvider and GetService<T>() if a dependency is truly optional.

Keyed services

Since .NET 8, services can be registered with a key, for cases with several implementations of one interface:

C#
builder.Services.AddKeyedSingleton<INotifier, EmailNotifier>("email");
builder.Services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
RAZOR
@code {
    [Inject(Key = "sms")] private INotifier Sms { get; set; } = default!;
}

The Key property on [Inject] selects the registration. This beats writing a factory class for simple "pick one by name" needs.

Design services around the interface the component needs (IProductService.GetAllAsync) rather than the machinery behind it (DbContext). Components that depend on narrow interfaces are trivial to test with a hand-written fake.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line makes a service available as a property named Products in a Razor file?

    @inject Type Name declares an injected property that the framework fills in before OnInitialized.
  2. 2. What is true about [Inject] properties on a component you create with new?

    Injection happens when the renderer creates the component; manually created instances get nothing.
  3. 3. OrderService's constructor needs IProductService and IClock. What must you register?

    The container resolves the graph, but every type in it must be registered or resolution fails.
  4. 4. Where do you put an @inject that every component in a folder needs?

    Directives in _Imports.razor are applied to all components below that folder.

Summary

  • Register interfaces and implementations on builder.Services; components ask for them with @inject or [Inject].
  • The container builds dependency graphs by reading constructors recursively; every dependency must be registered.
  • Never construct components with new: injection only happens when the framework creates them.
  • Use keyed services for several implementations of one contract.
  • Depend on narrow interfaces so components stay testable.

Next: Service Lifetimes and Scopes