Learn Blazor Β· 9/15

Dependency Injection (DI) & Services

7 min read

Dependency Injection (DI) & Services

Welcome back, developer! πŸš€ Today we are tackling one of the most intimidating-sounding topics in software engineering: Dependency Injection.

It sounds like a complex medical procedure involving a large needle πŸ’‰, but in reality, it is simply a way to organize your code so your components aren't glued together with superglue.

If you master this, you move from "Junior Developer who writes 5,000 lines of code in one file" to "Architect who builds scalable systems." Let's dive in.


1. Understanding Inversion of Control in Blazor

Before we inject anything, we need to understand the problem.

The Problem: Tight Coupling

Imagine you are building a Blazor component that displays a list of users. To get that data, your component needs to talk to a database or an API.

The "Bad" Way (Tight Coupling):
Inside your component, you manually create a new instance of the service.

csharp
// UserProfile.razor
@code {
    // πŸ›‘ PROBLEM: This component is now married to UserService.
    // You cannot test this component without a real UserService.
    // You cannot easily swap this out for a different service later.
    var userService = new UserService(); 
    var user = userService.GetUser(1);
}

This violates the Dependency Inversion Principle. Your component takes on the responsibility of creating its dependencies. It’s like a chef having to build a stove before they can cook a meal.

The Solution: Inversion of Control (IoC)

Definition: Inversion of Control is a design principle where the control of object creation and flow is transferred from the programmer to a container or framework.

In Blazor, instead of using the new keyword to create a service, you ask the Blazor framework to give it to you.

The "Good" Way:

csharp
// You don't create it. You just ask for it.
// Blazor says: "Here is the service you requested."
@inject IUserService UserService

🧠 Real Life Analogy

  • Without DI: You want a pizza. You buy flour, grow tomatoes, milk a cow for cheese, build an oven, and bake it.
  • With DI: You call a pizza shop. You don't care how they made it or what oven they used. You just asked for IPizzaService, and the delivery driver (the Injector) handed it to you.

2. Service Lifetimes: Singleton, Scoped, and Transient

When you ask Blazor for a service, how long does that service live? Does everyone share the same one? Do you get a brand new one?

This is defined by Service Lifetimes. Choosing the wrong one is the #1 cause of "Why is user A seeing User B's data?" bugs. πŸ›

The Three Musketeers of Lifetimes

1. Transient (AddTransient) ⚑

  • Definition: A new instance of the service is created every time it is requested.
  • Behavior: It is lightweight and stateless.
  • Analogy: A tissue. You grab one, use it, and throw it away. Next time, you grab a fresh one.
  • Use Case: Simple calculations, converters, or stateless operations.

2. Scoped (AddScoped) πŸ›’

  • Definition: A new instance is created once per "scope."
  • Blazor Server Behavior: The "scope" is the Circuit (the user's connection via SignalR). The service lives as long as the user's tab is open and connected.
  • Blazor WebAssembly Behavior: Since WASM runs in the browser, "Scoped" acts very similar to Singleton because the "scope" is the lifetime of the application in that specific browser tab.
  • Analogy: A shopping cart. It persists while you walk around the store (the session), but once you leave (disconnect), it's gone.
  • Use Case: User preferences, shopping carts, current navigation state.

3. Singleton (AddSingleton) 🏰

  • Definition: A single instance is created the first time it is requested, and that same instance is used by every single component and every single user (in Blazor Server).
  • Behavior: Global state.
  • Analogy: A Bank Vault. Everyone walks into the same bank and looks at the same vault.
  • Use Case: Caching data, configuration settings that never change.

⚠️ WARNING for Blazor Server: If you use Singleton to store user data (like CurrentUser), EVERY user connected to your server will become that user. You will accidentally leak personal data. Never use Singleton for user-specific state in Blazor Server.


3. Registering Services in Program.cs

Before you can inject a service, you must register it in the dependency injection container. This usually happens in Program.cs.

We typically use Interfaces for registration.

  • Interface: IMessageService (The contract/menu).
  • Implementation: EmailMessageService (The actual code).

This allows you to swap EmailMessageService with SmsMessageService later without changing a single line of code in your UI components!

Industry Standard Setup

Here is how you register services in a modern .NET 6/7/8+ Program.cs file.

csharp
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MyApp;
using MyApp.Services; // Assuming your services are here

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

// ---------------------------------------------------------
// πŸ› οΈ REGISTRATION HAPPENS HERE
// ---------------------------------------------------------

// 1. Transient: Fresh copy every time
builder.Services.AddTransient<IRandomNumberGenerator, RandomNumberGenerator>();

// 2. Scoped: Kept alive for the user session (Standard for Blazor App State)
builder.Services.AddScoped<ICartService, CartService>();

// 3. Singleton: Created once, lives forever
builder.Services.AddSingleton<IVersionService, VersionService>();

// ---------------------------------------------------------

await builder.Build().RunAsync();

Did you know? 🀯 The term "Dependency Injection" was coined by Martin Fowler. Before that, people just called it "don't hardcode your objects, please."


4. Injecting Services into Components using @inject

Now that we have registered the services, let's use them in our components.

Scenario

We have registered a TimeService (Scoped) that tells us the current time.

Approach A: The Razor Directive (Most Common)

Use @inject at the top of your .razor file.

csharp
@page "/time-tracker"
@using MyApp.Services

@* Format: @inject <InterfaceType> <PropertyName> *@
@inject ITimeService TimeService

<h3>Current Time</h3>
<p>The time is: @currentTime</p>

@code {
    private string currentTime;

    protected override void OnInitialized()
    {
        // usage: We just use the property 'TimeService'
        currentTime = TimeService.GetCurrentTime();
    }
}

Approach B: Constructor Injection (Standard C# Classes)

Sometimes you have a class (not a UI component) that needs a service. You can't use @inject there. You must use the constructor.

csharp
public class UserSettings
{
    private readonly ITimeService _timeService;

    // The container sees this constructor and automatically 
    // passes the ITimeService instance. Magic! πŸͺ„
    public UserSettings(ITimeService timeService)
    {
        _timeService = timeService;
    }
}

Approach C: Property Injection (Code-Behind Files)

If you prefer separating your C# code into a .razor.cs file, use the [Inject] attribute.

csharp
using Microsoft.AspNetCore.Components;

public partial class TimeTracker : ComponentBase
{
    [Inject]
    public ITimeService TimeService { get; set; }

    protected override void OnInitialized()
    {
        var time = TimeService.GetCurrentTime();
    }
}

5. Practical Example: A State Container

A very common requirement in Blazor is sharing data between two pages (e.g., a Product List page and a Checkout Sidebar). We use a Scoped Service for this.

1. Create the Service:

csharp
public class CartState
{
    // The actual state
    public List<string> Items { get; private set; } = new List<string>();

    // An event to notify components when data changes
    public event Action OnChange;

    public void AddItem(string item)
    {
        Items.Add(item);
        NotifyStateChanged();
    }

    private void NotifyStateChanged() => OnChange?.Invoke();
}

2. Register it (Program.cs):

csharp
builder.Services.AddScoped<CartState>();

3. Use it in Component A (Store.razor):

csharp
@inject CartState Cart
<button @onclick="() => Cart.AddItem('Laptop')">Add Laptop</button>

4. Use it in Component B (CartIcon.razor):

csharp
@inject CartState Cart
@implements IDisposable

<p>Items in cart: @Cart.Items.Count</p>

@code {
    protected override void OnInitialized()
    {
        // Subscribe to changes so the UI updates automatically
        Cart.OnChange += StateHasChanged;
    }

    public void Dispose()
    {
        // Always unsubscribe to prevent memory leaks!
        Cart.OnChange -= StateHasChanged;
    }
}

πŸ“š Summary

  1. IoC: Don't use new Service(). Let Blazor give it to you.
  2. Transient: New instance every request.
  3. Scoped: New instance per user session (Circuit). Best for state management.
  4. Singleton: One instance for the whole app. Dangerous for user data in Blazor Server.
  5. Program.cs: Where you register your services using interfaces.
  6. @inject: The magic word to get your service into a razor file.

πŸ”— Further Reading & References

Now go forth and inject responsibly! πŸ’‰βœ¨

Challenge

Challenge Instructions

You are tasked with building a shared state management system for a user's theme preference (e.g., 'dark' or 'light' mode) in a Blazor application. This requires creating a service to hold the theme state, registering it with the correct lifetime for user-specific data, and injecting it into two separate components.

One component, ThemeSelector, will allow the user to change the theme. The other component, LayoutView, will display the currently selected theme. The components must react instantly to changes made in the service.

Requirements:

  1. Services/IThemeState.cs: Define an interface IThemeState with the following members:

    • A string property named CurrentTheme.
    • A method SetTheme(string newTheme).
    • An event Action OnChange.
  2. Services/ThemeState.cs: Create a class ThemeState that implements IThemeState. The SetTheme method should update the CurrentTheme and invoke the OnChange event.

  3. Program.cs: Register the ThemeState service with the dependency injection container. You must choose the correct service lifetime that ensures each user has their own separate theme state, preventing data from leaking between different users' sessions.

  4. Components/ThemeSelector.razor: This component must:

    • Inject the IThemeState service.
    • Contain a button or mechanism that, when clicked, calls the SetTheme method on the service, toggling the theme between 'dark' and 'light'.
  5. Components/LayoutView.razor: This component must:

    • Inject the IThemeState service.
    • Display the value of the CurrentTheme property.
    • Subscribe to the OnChange event when the component is initialized to automatically re-render when the theme changes.
    • Crucially, it must properly unsubscribe from the OnChange event when the component is disposed to prevent memory leaks.

Expected result

The final code should correctly implement a shared state service using Dependency Injection.

  1. Program.cs must contain the line builder.Services.AddScoped<IThemeState, ThemeState>();. Using AddScoped is the correct lifetime for user-specific data in a Blazor Server application.

  2. IThemeState.cs must define the interface with a string property CurrentTheme, a method void SetTheme(string newTheme), and an event Action OnChange.

  3. ThemeState.cs must implement the IThemeState interface. The CurrentTheme property should be initialized to "light". The SetTheme method must update the CurrentTheme property and invoke the OnChange event (e.g., OnChange?.Invoke();).

  4. ThemeSelector.razor must inject the service using @inject IThemeState ThemeState. The ToggleTheme method should check the current theme and call ThemeState.SetTheme() with the opposite value (e.g., if CurrentTheme is "light", call SetTheme("dark")).

  5. LayoutView.razor must:

    • Inject the service using @inject IThemeState ThemeState.
    • Display the theme with @ThemeState.CurrentTheme.
    • In OnInitialized(), it must subscribe to the event: ThemeState.OnChange += StateHasChanged;.
    • In Dispose(), it must unsubscribe from the event: ThemeState.OnChange -= StateHasChanged;.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.