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.
// 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:
// 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
Singletonto store user data (likeCurrentUser), 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.
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.
@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.
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.
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:
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):
builder.Services.AddScoped<CartState>();3. Use it in Component A (Store.razor):
@inject CartState Cart
<button @onclick="() => Cart.AddItem('Laptop')">Add Laptop</button>4. Use it in Component B (CartIcon.razor):
@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
- IoC: Don't use
new Service(). Let Blazor give it to you. - Transient: New instance every request.
- Scoped: New instance per user session (Circuit). Best for state management.
- Singleton: One instance for the whole app. Dangerous for user data in Blazor Server.
- Program.cs: Where you register your services using interfaces.
- @inject: The magic word to get your service into a razor file.
π Further Reading & References
- Official Microsoft Docs: Blazor Dependency Injection
- Service Lifetimes Deep Dive
- Dependency Injection in ASP.NET Core
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:
Services/IThemeState.cs: Define an interfaceIThemeStatewith the following members:- A
stringproperty namedCurrentTheme. - A method
SetTheme(string newTheme). - An event
Action OnChange.
- A
Services/ThemeState.cs: Create a classThemeStatethat implementsIThemeState. TheSetThememethod should update theCurrentThemeand invoke theOnChangeevent.Program.cs: Register theThemeStateservice 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.Components/ThemeSelector.razor: This component must:- Inject the
IThemeStateservice. - Contain a button or mechanism that, when clicked, calls the
SetThememethod on the service, toggling the theme between 'dark' and 'light'.
- Inject the
Components/LayoutView.razor: This component must:- Inject the
IThemeStateservice. - Display the value of the
CurrentThemeproperty. - Subscribe to the
OnChangeevent when the component is initialized to automatically re-render when the theme changes. - Crucially, it must properly unsubscribe from the
OnChangeevent when the component is disposed to prevent memory leaks.
- Inject the
Expected result
The final code should correctly implement a shared state service using Dependency Injection.
Program.csmust contain the linebuilder.Services.AddScoped<IThemeState, ThemeState>();. UsingAddScopedis the correct lifetime for user-specific data in a Blazor Server application.IThemeState.csmust define the interface with a string propertyCurrentTheme, a methodvoid SetTheme(string newTheme), and an eventAction OnChange.ThemeState.csmust implement theIThemeStateinterface. TheCurrentThemeproperty should be initialized to "light". TheSetThememethod must update theCurrentThemeproperty and invoke theOnChangeevent (e.g.,OnChange?.Invoke();).ThemeSelector.razormust inject the service using@inject IThemeState ThemeState. TheToggleThememethod should check the current theme and callThemeState.SetTheme()with the opposite value (e.g., ifCurrentThemeis "light", callSetTheme("dark")).LayoutView.razormust:- 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;.
- Inject the service using