Covers who creates scopes and how long they last in message consumers, SignalR, Blazor Server circuits, Blazor WebAssembly, console apps and tests, with the typical bugs: long-lived DbContexts per circuit, missing scopes and root resolution.
A scope lasts exactly as long as whoever created it decides. ASP.NET Core creates one per request; other hosts differ:
CreateAsyncScope() itself.DbContext becomes long-lived and shared across UI events. Use IDbContextFactory<T> or OwningComponentBase.The trade-off: longer scopes give continuity of state, but stale data, memory and concurrency problems.
"A scope is just a container boundary that somebody opens and closes. In ASP.NET Core the framework opens one per request, and that's the model most people carry around. Outside HTTP you have to ask who opens the scope and how long it stays open.
For messaging, the good frameworks open one per message: MassTransit, NServiceBus, Azure Functions with the isolated worker all do this, so a consumer can take a
DbContextin its constructor. If I write my own consumer on top of the Azure Service Bus SDK, nobody does it for me, so the processor callback creates an async scope per message. SignalR creates a scope per hub method invocation, and hubs are transient, so state goes in a store keyed by connection id, never in hub fields.Blazor Server is the surprising one. The scope is the circuit: the user's SignalR connection to the server. That can be open for hours, so a scoped
DbContextlives for hours, accumulates tracked entities, and can be hit by two UI events at once, which throws the 'second operation' error. Microsoft's guidance is to useIDbContextFactory<T>and create a context per operation, orOwningComponentBaseto tie a scope to a component. Blazor WebAssembly runs in the browser for one user, so scoped and singleton are effectively the same. In a console app or a test there's only the root until you create scopes yourself.The mistake I see is code written for per-request scopes being reused unchanged in one of these hosts. For example, at [company] we [moved a form from MVC to Blazor Server and the injected DbContext started showing users stale data after they had been on the page for a while]. Always ask how long the scope lives."
| Host | Created by | Lifetime of a scope | Typical bug |
|---|---|---|---|
| ASP.NET Core request | Framework | One request | Fire-and-forget after response |
| MassTransit / NServiceBus / Functions | Framework | One message | Sharing state across messages in singletons |
| Hand-rolled Service Bus / Kafka consumer | You | What you choose | No scope: scoped resolved from root |
| SignalR hub | Framework | One hub method call | State in hub fields lost between calls |
| Blazor Server | Framework | The circuit (minutes to hours) | Long-lived DbContext, concurrent UI events |
| Blazor WebAssembly | Framework | The browser tab | Expecting per-request behaviour |
| Console app / worker | You | What you choose | Root-only resolution |
Integration tests (WebApplicationFactory) |
Framework per request; you for direct access | Per request / per test | Resolving scoped from factory.Services (root) |
In a Blazor Server back-office app, users who kept a customer page open over lunch saw [stale balances] and occasionally an error when two buttons were clicked quickly. Switching components to IDbContextFactory<T> with a context per operation removed the errors and reduced server memory per circuit from [~12 MB] to [~3 MB] across [~400] concurrent circuits.
Checks that the candidate understands scopes as brackets created by the host, and knows the per-host behaviour, especially Blazor Server circuits.
Green flags
IDbContextFactory<T>Red flags
DbContext straight into Blazor Server componentsfactory.Services in testsusing/await using (var scope = scopeFactory.CreateAsyncScope())
{
// scoped instances live here
} // disposed here
The framework or you decide where the brackets go. Everything else follows from that.
Service Bus processor callback (hand-rolled)
└─ await using scope = scopes.CreateAsyncScope()
handler = scope.Get<IHandler<OrderPlaced>>()
await handler.HandleAsync(msg)
await args.CompleteMessageAsync(msg)
With MaxConcurrentCalls = 8, eight callbacks run in parallel, each with its own scope. A scope must never be shared across messages processed concurrently.
The hub is created per invocation (transient) and resolved from a scope created per invocation. IHubContext<THub> (used to send from outside hubs) is a singleton. Connection state lives in Context.Items or an external store.
Browser ── SignalR connection ── Circuit (scope created here)
├─ scoped AppDbContext (lives with the circuit)
├─ component A event ─┐ can overlap
└─ component B event ─┘
Circuit ends (tab closed / disconnect timeout) → scope disposed
Options:
IDbContextFactory<T>: await using var db = await Factory.CreateDbContextAsync(); per operation (recommended).OwningComponentBase<T>: the component gets its own scope that is disposed with the component.The whole app runs in the browser for one user. There is no per-request scope; scoped services live for the tab's lifetime. Don't put server-side concerns (DbContext) there at all.
Host.CreateApplicationBuilder in a console app gives you a root provider; create a scope for each unit of work. In tests, WebApplicationFactory<T>.Services is the root; to use a scoped service directly in an arrange step:
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
Guid; open two tabs and refresh; compare ids per tab and across refreshes.DbContext quickly and reproduce the concurrency error; fix with IDbContextFactory<T>.MaxConcurrentCalls = 4 and log a scoped Guid per message.factory.Services with ValidateScopes on and read the error.A Blazor Server component using a context per operation, and a hand-rolled message consumer with a scope per message.
@* Customers.razor (Blazor Server) *@
@page "/customers/{Id:int}"
@using Microsoft.EntityFrameworkCore
@inject IDbContextFactory
DbContext directly into Blazor Server components. Why it is wrong: It lives for the whole circuit, accumulates tracked entities and is hit by overlapping UI events. Instead: IDbContextFactory<T> per operation, or OwningComponentBase.CreateAsyncScope() in the message callback.Context.Items, a scoped-per-connection store or an external cache.WebApplicationFactory.Services in tests. Why it is wrong: That is the root provider; validation throws or the instance leaks across tests. Instead: Create a scope in the test.DbContext and collide. Instead: One scope per message.Whenever code moves between hosts (MVC to Blazor, API to worker, HTTP to messaging) I re-check scope boundaries, because the code compiles and the tests pass while the lifetime semantics change underneath. The question to ask is "how long does a scope live here, and can two things run inside it at once?" Blazor Server answers "hours" and "yes", which is why the guidance there is per-operation contexts.
| Host | Recommended DbContext approach |
Why | Avoid |
|---|---|---|---|
| ASP.NET Core request | Scoped (AddDbContext) |
Request = unit of work | Parallel branches on one context |
| Message consumer framework | Scoped (framework scope per message) | Message = unit of work | Singletons holding contexts |
| Hand-rolled consumer | Scope per message | Same, done manually | Root resolution |
| Blazor Server | IDbContextFactory<T> per operation |
Circuit is long and concurrent | Injected scoped context |
| Blazor WebAssembly | Call an API; no DbContext |
Runs in the browser | Server-side data access |
Measure with memory per circuit or per consumer instance and EF concurrency exception counts after any host change.
The lifetime tells the container how long to reuse an instance:
HttpContext.RequestServices) and disposes it when the response finishes, so a DbContext is shared by everything in one request.A worker service has no requests, so there is no scope unless you create one with IServiceScopeFactory.CreateAsyncScope() per message or per loop iteration. The rule that ties it together: a service may only depend on services that live at least as long as it does.
SignalR is ASP.NET Core's real-time framework. A hub is a class whose public methods clients call, and the server calls methods on clients through Clients.All, Clients.Group(...) or Clients.User(...). Hubs are transient, created per invocation, so they hold no state. On connect the client calls negotiate and uses the best transport available: WebSockets, then Server-Sent Events, then long polling. Groups fan messages out to subsets of connections, but they live in memory, so a reconnecting client must re-join them (usually in OnConnectedAsync). Strongly typed hubs (Hub<IOrderClient>) replace method-name strings with an interface. Authentication uses the normal pipeline with [Authorize]. Browsers can't send an Authorization header on WebSockets or EventSource, so as a workaround the token travels as an access_token query parameter, read in JwtBearerEvents.OnMessageReceived.
The trade-off: reconnects and routing come free, but every client holds a stateful connection that you must plan to scale.
Good DI makes unit tests container-free: if a class takes its dependencies through the constructor, the test just calls new OrderService(fakeRepo, fakeClock).
For integration tests, WebApplicationFactory<Program> boots the real app and container in memory. In ConfigureTestServices, which runs after Program.cs registrations, you swap external boundaries: services.RemoveAll<IPaymentGateway>(); services.AddSingleton<IPaymentGateway, FakePaymentGateway>();.
Prefer fakes (in-memory implementations, FakeTimeProvider) for state, and mocks only to verify interactions at boundaries.
The trade-off: replacing too much tests your mocks instead of your app; replace only what crosses a process boundary.
How to tell it (STAR)
**S:** At [company], after we moved our customer screens from MVC to Blazor Server, staff started seeing [stale balances] and occasional errors when clicking quickly. **T:** I was asked to find out why the same data code behaved differently in the new UI. **A:** I reproduced both symptoms locally. In Blazor Server a scope is the user's circuit, not a request, so the injected DbContext lived for hours: its identity map served old rows, and two UI events could hit it at once. I switched the components to IDbContextFactory with a context per operation, used OwningComponentBase for the few edit forms that needed tracking, and added an analyser rule to stop direct DbContext injection in components. **R:** The stale-data reports and concurrency errors stopped, and memory per circuit dropped from [about 12 MB] to [about 3 MB].
Last updated 23 Nov 2026.