skip to content

In a Blazor Web App, what does AddScoped mean on Interactive Server and on WebAssembly, and how do you build a shared cake-basket state container safely?

level: middleimportance: must knowfreq 64%

answer

  1. server: one scope per circuit
  2. WebAssembly: scoped behaves like singleton
  3. server singleton: shared by every user
  4. event Action? Changed + Dispose unsubscribe
  5. InvokeAsync(StateHasChanged) from the handler

basics

~20 s

On Interactive Server a scoped service lives as long as the user's circuit; in WebAssembly there are no DI scopes, so scoped acts like a singleton for that tab. Register the basket as scoped, raise an event on change, and have components subscribe and unsubscribe.

solid answer

~40 s

Blazor reuses ASP.NET Core's DI lifetimes with different boundaries. On **Interactive Server** the DI scope is the **circuit**, so a scoped service is created once per tab and shared by every component in it across in-app navigation. In **WebAssembly** there is no scope, so scoped behaves like singleton for that browser tab. A **singleton** on the server is shared by every user of the app, so a singleton basket mixes customers' orders. The usual pattern is a scoped `CakeBasket` holding the lines and an `event Action? Changed`; components subscribe in `OnInitialized`, call `InvokeAsync(StateHasChanged)` from the handler, and unsubscribe in `Dispose`, or the circuit keeps them alive. Disposable transient services are also held for the whole circuit, so avoid them.

code

csharp · 16 lines
csharp
public sealed class CakeBasket
{
    private readonly List<CakeLine> lines = [];

    public IReadOnlyList<CakeLine> Lines => lines;
    public event Action? Changed;

    public void Add(CakeLine line)
    {
        lines.Add(line);
        Changed?.Invoke();
    }
}

// Program.cs
builder.Services.AddScoped<CakeBasket>();

go deeper

for a junior

Recall that scoped means per circuit on the server and effectively per tab in WebAssembly, and that singletons on the server are shared by all users.

for a middle

Explain the lifetime table across static SSR, Interactive Server and WebAssembly, and build a state container with an event and unsubscribe.

for a senior

Spot singleton leaks, disposable transients held per circuit, the separate prerender scope, and when OwningComponentBase fits better.

for a principal

Decide where shared client state lives across render modes so moving a page from WebAssembly to Server cannot change who sees it.

## The same lifetimes, different boundaries Blazor uses `AddSingleton`, `AddScoped` and `AddTransient` exactly as ASP.NET Core does, but where a scope starts and ends depends on where the component runs: | Lifetime | Static SSR | Interactive Server | WebAssembly | |---|---|---|---| | Singleton | One per app process | One per app process, **shared by every user** | One per browser tab | | Scoped | One per HTTP request | One per **circuit** (per tab, per user) | No scopes: behaves like singleton | | Transient | New per resolution | New per resolution; disposables held until the circuit ends | New per resolution; disposables held for the app's life | On Interactive Server, navigating between components does not create a new scope, because the traffic travels over the circuit's SignalR connection rather than as new HTTP requests. A new scope, and therefore new scoped services, appears only with a new circuit: a reload, a new tab, or a reconnect that fails. ## Why a singleton basket is a bug on the server A singleton is created once for the whole server process. Registering `CakeBasket` with `AddSingleton` on Interactive Server means every visitor adds cakes to the **same** basket, which is both a privacy defect and a concurrency hazard, since several circuits mutate one list at once. The same registration in a WebAssembly app looks fine because each tab has its own runtime, which is exactly why the bug often appears only after a component moves to Interactive Server or Auto. ## Building the state container A **state container** is a scoped service that holds shared state and announces changes: 1. Register it: `builder.Services.AddScoped<CakeBasket>();` (in both projects when the app uses WebAssembly too). 2. Keep the data private and expose read-only views plus methods that change it. 3. Raise an event such as `event Action? Changed` after every mutation. 4. In each component, subscribe in `OnInitialized` and unsubscribe in `Dispose`. 5. In the handler, call `InvokeAsync(StateHasChanged)`, because the event may be raised from another component's handler or a background task, and rendering must happen on the component's dispatcher. ## Why unsubscribing matters The scoped service lives as long as the circuit. When a component subscribes, the service's event holds a reference to that component. If the component is removed without unsubscribing, the service keeps it alive, and it keeps receiving notifications and calling `StateHasChanged` on a disposed instance, until the user closes the tab. Implement `IDisposable` and remove the handler. ## Checklist for a basket container - Register it scoped, in the server project and in the `.Client` project if WebAssembly components use it. - Expose read-only views; mutate only through methods that raise the change event. - Raise the event after the state is consistent, never halfway through an update. - Keep it free of UI types such as `RenderFragment`; it should be plain data plus behaviour. - Decide what must outlive the circuit and persist that separately: the container itself is memory only. - If Interactive Server and WebAssembly components both show the basket, remember they run in different runtimes and hold different instances; share through persistence or an API, not through the container. ## Related lifetime traps on the server - **Disposable transients** are tracked by the container and kept until the circuit ends, so they leak for as long as the user stays; prefer scoped, or a factory the component disposes. - **Scoped services longer than a component** - a scoped service injected into a page lives for the whole circuit, not the page. For a service whose lifetime should match one component, derive from `OwningComponentBase`, which creates a DI scope per component instance. - **Prerendering creates a separate scope.** The prerender pass runs in the HTTP request's scope; the interactive circuit gets a new one. A basket filled during prerendering is not the instance the interactive components see. - **Two tabs, two baskets.** Each tab has its own circuit; a basket that must follow the user across tabs belongs in a database or browser storage.

  • A basket registered with AddSingleton worked in WebAssembly testing but in production customers saw each other's cakes once the page used InteractiveServer; why?
    In WebAssembly each tab has its own runtime, so a singleton is effectively per user. On Interactive Server the singleton lives once in the server process and every circuit resolves the same instance. Register the basket with `AddScoped` so each circuit gets its own.
  • Why does a header badge keep updating, and memory keep growing, after users leave the page that subscribed to the basket?
    The scoped basket outlives the page, and its `Changed` event still references the old component because it never unsubscribed. The component stays reachable and keeps handling events. Implement `IDisposable` and remove the handler in `Dispose`.

  • Scoped on Interactive Server means one instance per HTTP request.
  • Scoped services are recreated on every page navigation in the circuit.
  • A singleton basket is fine on the server because each user has a circuit.
  • WebAssembly creates a new scope for each component.
  • Event subscriptions to a scoped service are removed automatically when a component is disposed.