Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 41 ยท State and Dependency Injection

Service Lifetimes and Scopes in Blazor

Understand singleton, scoped and transient services in Blazor Server and WebAssembly, how a circuit acts as a scope, captive dependencies and disposing services correctly.

When a component asks for a service, a second question hides behind it: which instance do I get, and for how long does it live? The answer is the service's lifetime. Choose well and you share expensive objects safely; choose badly and users see each other's data, or the app leaks memory.

Blazor makes this topic trickier than in a normal web app because the meaning of "scoped" depends on where your code runs. This lesson defines the three lifetimes, shows what a scope is in Blazor Server, WebAssembly and static server rendering, explains the captive dependency trap and the OwningComponentBase helper, and ends with a runnable stand-in that makes the rules visible.

The three lifetimes

Lifetime Registration New instance when...
Singleton AddSingleton<T>() once for the whole application
Scoped AddScoped<T>() once per scope
Transient AddTransient<T>() every time it is requested

A scope is a container for scoped services: everything resolved in it shares the same scoped instances, and when the scope ends, its disposable instances are disposed. In a classic MVC app a scope equals one HTTP request. In Blazor it depends on the hosting model.

What is a scope in Blazor?

  • Blazor Server / Interactive Server: the scope is the circuit, the live SignalR connection between one browser tab and the server. A scoped service lives as long as the user keeps that tab connected, perhaps for hours. It is effectively "per user session", which makes scoped services the natural place for per-user state.
  • Blazor WebAssembly: there is only one user, and the app runs in their browser. Scoped services behave like singletons: the scope is the whole app. They do not follow navigation.
  • Static server-side rendering (SSR): each HTTP request gets its own scope, just like MVC. Nothing survives between requests.
  • Interactive Auto / WebAssembly in a Blazor Web App: services are registered in both projects, and the same interface may be a scoped per-circuit service on the server and an app-lifetime service in the browser. Write code that works under both meanings.
flowchart TB
    S["Singleton<br/>one per app, shared by all users"] --> C1["Circuit A scope<br/>user A's tab"]
    S --> C2["Circuit B scope<br/>user B's tab"]
    C1 --> T1["Transient instances<br/>new every request"]
    C2 --> T2["Transient instances"]

Singletons are shared by everyone; scoped services are per circuit; transients are new each time.

Choosing a lifetime

  • Singleton: stateless helpers, caches that are the same for every user, configuration wrappers. Must be thread-safe, because many circuits call it at once.
  • Scoped: anything per user or per session: shopping cart, current-user info, a DbContext (with a caveat below).
  • Transient: lightweight, stateless, no sharing needed. Each consumer gets its own.
C#
builder.Services.AddSingleton<IExchangeRates, RatesCache>();    // same data for all
builder.Services.AddScoped<ICart, Cart>();                      // one cart per circuit
builder.Services.AddTransient<IPriceFormatter, PriceFormatter>();

The singleton-state mistake

Putting per-user data in a singleton is the most dangerous Blazor bug. A singleton Cart on a Blazor Server app would show everyone the same cart. Test with two browsers whenever you write state.

Captive dependencies

A longer-lived service must not hold a shorter-lived one. If a singleton takes a scoped service in its constructor, the first scope's instance is captured forever, shared with every user. ASP.NET Core catches this in the Development environment (scope validation) and throws, but only if you let it. Keep it enabled.

C#
public class Notifier(ICart cart) { }       // BAD if Notifier is a singleton and ICart is scoped

The remedy is to inject IServiceScopeFactory and create a scope for the short operation, or to redesign so the singleton does not need the scoped service.

DbContext in Blazor Server

An EF Core DbContext is normally scoped, but a circuit lasts for hours and the context is not thread-safe. Components that run overlapping async operations on one shared context throw "A second operation was started on this context". Use IDbContextFactory<T> and create a short-lived context per operation instead:

RAZOR
@inject IDbContextFactory<ShopContext> Factory

@code {
    private async Task LoadAsync()
    {
        await using var db = await Factory.CreateDbContextAsync();
        orders = await db.Orders.ToListAsync();
    }
}

This is Microsoft's recommended pattern for Blazor Server. Alternatively, derive from OwningComponentBase<T>: it creates a scope for the component itself, so the injected service lives exactly as long as that component.

Disposal

If a service implements IDisposable or IAsyncDisposable, the container disposes it when its scope ends, but only if the container created it. If you register an instance (AddSingleton(new Thing())), you own it. Components that implement IDisposable are disposed when removed from the render tree: this is where you unsubscribe from events and cancel work. Transient disposables injected into a long-lived scope pile up until the circuit ends, a subtle leak; prefer a factory for short-lived disposables.

See lifetimes in action

The stand-in container below supports singleton, scoped and transient with explicit scopes, so you can create "two circuits" and check which instances are shared.

C# Singleton, scoped and transient

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.

Read the output: one singleton for everybody, one scoped instance per circuit, two transients created inside circuit A. Disposal covers every instance the scope created (note the transients: they were kept alive until the scope ended).

A captive dependency, caught

The next stand-in adds the check that ASP.NET Core performs in Development: when resolving a singleton, refuse any dependency whose lifetime is shorter.

C# Detecting a captive dependency

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.

Never turn off scope validation (ValidateScopes = false) to make an error go away. The error is telling you that one user's data may leak into another user's session.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Blazor Server, what does a scoped service live as long as?

    Each browser tab gets a circuit, and the circuit is the DI scope.
  2. 2. How do scoped services behave in Blazor WebAssembly?

    WebAssembly runs a single user's app, and its scope is the entire app lifetime.
  3. 3. A singleton service takes a scoped service in its constructor. What is the problem?

    The singleton outlives the scope and keeps one scoped instance forever.
  4. 4. What is the recommended way to use EF Core in Blazor Server components?

    A context is not thread-safe and circuits are long-lived, so create one per unit of work.

Summary

  • Singleton = one for the app, scoped = one per scope, transient = new each time.
  • A Blazor Server scope is the circuit; in WebAssembly it is the whole app; in static SSR it is the request.
  • Per-user state belongs in scoped services, never singletons.
  • A longer-lived service must not depend on a shorter-lived one; keep scope validation on.
  • Use IDbContextFactory and dispose what you create.

Next: Component State and Cascading Values