📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What does a DI scope mean outside an HTTP request? Explain how scopes work in message consumers, SignalR hubs, Blazor Server (and why scoped means per circuit there), Blazor WebAssembly, console apps and tests, and the bugs each one invites.

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.

Mid-Level Theory Intermediate blazor dependency-injection messaging service-scopes signalr testing

🎯 Key points

  • A scope lasts as long as whoever created it decides; only some hosts create them for you
  • Message consumers: frameworks such as MassTransit, NServiceBus and Azure Functions manage one scope per message; hand-rolled consumers must create their own
  • SignalR: a new scope per hub method invocation; hubs are transient, so don't keep state in hub fields
  • Blazor Server: one scope per circuit (the user's connection), so scoped services can live for hours and see concurrent UI events; use IDbContextFactory<T> or OwningComponentBase
  • Blazor WebAssembly: each browser tab is its own app instance with a single scope, so scoped behaves like singleton within that tab (Microsoft docs)
  • Console apps and tests: the root provider only, so create scopes explicitly; WebApplicationFactory.Services is the root
  • Long-lived scopes cost memory; many short scopes cost a small allocation each, which is almost always the better trade
  • Typical bugs: long-lived DbContext per circuit, scoped resolved from root, sharing a scope across concurrent messages

⏱ 30-second answer

A scope lasts exactly as long as whoever created it decides. ASP.NET Core creates one per request; other hosts differ:

  • Message consumers: MassTransit, NServiceBus and Azure Functions create a scope per message; a hand-rolled consumer must call CreateAsyncScope() itself.
  • SignalR: a scope per hub method call; the hub is transient, so no state in fields.
  • Blazor Server: a scope per circuit, which is the user's connection and can last hours, so a scoped DbContext becomes long-lived and shared across UI events. Use IDbContextFactory<T> or OwningComponentBase.
  • Blazor WebAssembly: one user per process, so scoped is effectively singleton.
  • Console apps and tests: only the root provider exists until you create scopes.

The trade-off: longer scopes give continuity of state, but stale data, memory and concurrency problems.

🗣 Full answer (senior)

How I would answer this in an interview

"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 DbContext in 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 DbContext lives 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 use IDbContextFactory<T> and create a context per operation, or OwningComponentBase to 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."


Who creates the scope, and for how long

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)

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands scopes as brackets created by the host, and knows the per-host behaviour, especially Blazor Server circuits.

Green flags

  • Asks "who creates the scope and how long does it live?"
  • Knows Blazor Server scoped = per circuit and recommends IDbContextFactory<T>
  • Mentions concurrency inside a scope (overlapping UI events, parallel message handlers), not just duration
  • Knows SignalR hubs are transient with a scope per invocation
  • Creates scopes explicitly in hand-rolled consumers and tests

Red flags

  • Assumes every host has per-request scopes
  • Injects DbContext straight into Blazor Server components
  • Resolves scoped services from factory.Services in tests

📚 Learn in depth

1. A scope is a bracket

using/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.

2. Messaging

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.

3. SignalR

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.

4. Blazor Server circuits

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.
  • Disconnected circuits are retained for a period (by default 3 minutes) before disposal, so scoped memory outlives the tab briefly.

5. Blazor WebAssembly

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.

6. Console apps and tests

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>();

Try it yourself

  1. In a Blazor Server app, inject a scoped service holding a Guid; open two tabs and refresh; compare ids per tab and across refreshes.
  2. Click two buttons that both query the injected DbContext quickly and reproduce the concurrency error; fix with IDbContextFactory<T>.
  3. Write a Service Bus processor with MaxConcurrentCalls = 4 and log a scoped Guid per message.
  4. In an integration test, resolve a scoped service from factory.Services with ValidateScopes on and read the error.

💻 Code

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

⚠ Common mistakes

  • Mistake: Injecting a 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.
  • Mistake: Assuming a hand-rolled Service Bus or Kafka consumer gets a scope per message. Why it is wrong: Only frameworks like MassTransit or Functions do that; otherwise you resolve from the root. Instead: CreateAsyncScope() in the message callback.
  • Mistake: Keeping state in SignalR hub fields. Why it is wrong: Hubs are transient per invocation; the field is gone on the next call. Instead: Context.Items, a scoped-per-connection store or an external cache.
  • Mistake: Treating Blazor WebAssembly scoped services as per-request. Why it is wrong: There is one scope for the tab; scoped equals singleton. Instead: Design state for the tab's lifetime.
  • Mistake: Resolving scoped services from 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.
  • Mistake: Sharing one scope across concurrent message handlers. Why it is wrong: The handlers share a DbContext and collide. Instead: One scope per message.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate defines scope only in terms of HTTP requests Why: Checks the basic lifetime definitions
    How to answer

    The lifetime tells the container how long to reuse an instance:

    • Singleton: one instance for the whole app (per root provider), created on first use and disposed when the host stops.
    • Scoped: one instance per scope. In ASP.NET Core the framework creates a scope per HTTP request (HttpContext.RequestServices) and disposes it when the response finishes, so a DbContext is shared by everything in one request.
    • Transient: a new instance every time it is resolved, disposed with the scope that created it.

    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.

  2. When: Candidate mentions SignalR hubs Why: Checks SignalR architecture knowledge
    How to answer

    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.

  3. When: Candidate mentions integration tests Why: Checks DI in testing with WebApplicationFactory
    How to answer

    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.

🛠 Real-world problems: how you handle them

Stale data and concurrency errors after moving a form to Blazor Server
Situation
[Back-office customer management app, ~400 concurrent Blazor Server circuits during business hours, Azure App Service Australia East]. Pages were ported from MVC and kept injecting the scoped AppDbContext into components.
Signals
Staff reported balances that didn't update until they refreshed the browser; Application Insights logged 'A second operation was started on this context instance' when users clicked two buttons quickly; server memory grew with the number of open circuits [~12 MB each].
Investigation
Reproduced locally: kept a page open, changed the row in SQL, clicked Refresh and saw the old value (identity map in a circuit-long context). Double-clicking two actions reproduced the concurrency error. A dotnet-gcdump showed AppDbContext instances per circuit holding thousands of tracked entities. Confirmed from Microsoft's Blazor guidance that scoped services live per circuit.
Resolution
Registered AddDbContextFactory and changed components to create a context per operation with await using, reads with AsNoTracking. Long-running edit forms that needed change tracking used OwningComponentBase so the scope ends with the component.
Prevention
Analyser rule flagging @inject AppDbContext in .razor files; a team guideline page on scope lifetimes per host; a memory-per-circuit dashboard in Application Insights.

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].

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me