Why does injecting a DbContext directly into Blazor Interactive Server components fail under concurrent use, and how does IDbContextFactory fix it?
answer
- AddDbContext is scoped = one per circuit
- "A second operation was started on this context"
- IDbContextFactory<TContext> is a singleton
- await using var db = await factory.CreateDbContextAsync()
- per operation, or per editing component
basics
~10 sAddDbContext registers a scoped DbContext, and on Interactive Server a scope is the whole circuit, so every component shares one non-thread-safe context. Inject IDbContextFactory<TContext> instead and create a short-lived context per operation with CreateDbContextAsync.
solid answer
~40 s`AddDbContext` registers the context as scoped, which in an MVC or API app means per request. On Interactive Server the scope is the **circuit**, so every component in the user's tab shares one `DbContext` for minutes or hours. `DbContext` is not thread safe: two overlapping async operations, such as an order list loading while a header component counts cakes, throw `InvalidOperationException` ("A second operation was started on this context instance before a previous operation completed"), and the long-lived change tracker serves stale entities and grows. Register `AddDbContextFactory<TContext>` and inject `IDbContextFactory<TContext>`; each operation does `await using var db = await DbFactory.CreateDbContextAsync();`. When an editing component needs change tracking across several steps, create one context in `OnInitialized` and dispose it with the component.
code
razor · 16 lines@page "/orders"
@rendermode InteractiveServer
@inject IDbContextFactory<PatisserieDb> DbFactory
@code {
private List<CakeOrder> orders = [];
protected override async Task OnInitializedAsync()
{
await using var db = await DbFactory.CreateDbContextAsync();
orders = await db.CakeOrders
.AsNoTracking()
.Where(o => o.PickupDate >= DateOnly.FromDateTime(DateTime.Today))
.ToListAsync();
}
}go deeper
Recall that Blazor Server components should inject IDbContextFactory and create a context per operation with await using.
Explain why scoped means per circuit, the second-operation exception, and stale tracked data in a long-lived context.
Choose between per-operation and per-component contexts, apply the same rule to services, and keep change tracking deliberate.
Set data-access conventions that hold across static SSR, Interactive Server and WebAssembly so a render-mode change cannot introduce shared contexts.
## Why the default registration misfits Blazor Server EF Core's `AddDbContext` registers the context with a **scoped** lifetime. In a controller or Minimal API, a scope is one HTTP request, so each request gets its own context and disposes it at the end. That fits the context's design: a short-lived **unit of work** that is not thread safe. On **Interactive Server**, the DI scope is the user's **circuit**. One context is created for the first component that asks and then shared by every component in that tab until the circuit ends. Three problems follow: | Problem | Symptom | |---|---| | Concurrent use | `InvalidOperationException`: "A second operation was started on this context instance before a previous operation completed..." | | Long-lived change tracker | Queries return entities tracked minutes ago instead of fresh values; memory grows | | One failed `SaveChanges` | Invalid tracked changes stay in the context and poison later saves for the whole circuit | Concurrency happens easily: a page and a layout component both load data in `OnInitializedAsync`, or a timer refreshes the cake counts while the user saves an order. Both use the one scoped context. The other lifetimes do not help either: a **singleton** context would be shared across all users, and a **transient** one is held as long as the component, which may live for the whole visit. ## IDbContextFactory Register the context with `AddDbContextFactory<PatisserieDb>(...)`, which by default registers `IDbContextFactory<PatisserieDb>` as a **singleton** (the factory is safe to share; the contexts it creates are not). Then: 1. Inject `IDbContextFactory<PatisserieDb>` into the component or service. 2. Create a context for one operation: `await using var db = await DbFactory.CreateDbContextAsync(cancellationToken);`. 3. Query or save, and let `await using` dispose it at the end of the block. Each operation now has its own context, so parallel loads cannot collide, every query sees current data, and a failed save affects only that operation. ## When one context per component is right Some screens edit an entity across several user steps and want EF Core's change tracking or optimistic concurrency handling for the whole edit, for example a cake order the customer adjusts before confirming. Then: - Create one context from the factory in `OnInitialized`. - Load the order with tracking and bind the form to it. - Call `SaveChangesAsync` when the user confirms. - Implement `IDisposable` or `IAsyncDisposable` and dispose the context with the component. - Guard against overlapping operations in that component, for example by ignoring a second save while one is running. `OwningComponentBase<TService>` offers a related tool: it creates a DI scope per component instance, so a scoped service resolved through it lives and dies with that component. ## Services used by components The same rule applies one level down. A scoped `OrderService` that injects the scoped `DbContext` inherits the problem, because the service is per circuit too. Have such services take `IDbContextFactory<TContext>` and create a context inside each method. ## Diagnosing it in a running app - **The second-operation exception appears only under real traffic.** Locally one component loads at a time; in production a layout, a page and a timer overlap. Look for every `@inject PatisserieDb` and every scoped service holding the context. - **Memory grows per user over a long session.** A circuit-scoped context keeps every entity it has tracked; the change tracker is a cache nobody clears. - **A save fails and every later save in that tab fails too.** The invalid entity remains tracked in the shared context. - **Data looks stale until the user reloads.** The reload creates a new circuit and therefore a new context, which is exactly the hint that the context lived too long. All four disappear once each operation creates and disposes its own context from the factory. ## What does not change - Static SSR pages run per request, so a scoped context there behaves as in MVC; the factory still works and keeps code uniform. - In WebAssembly components, EF Core usually is not used directly against a server database; the component calls a web API, which uses its own per-request context. - Pooling (`AddPooledDbContextFactory`) reduces allocation cost but does not change the per-operation rule.
- The orders page and a basket badge in the layout both query the database in OnInitializedAsync and the page intermittently throws; what is happening?Both components resolve the same circuit-scoped `DbContext` and their async queries overlap, which EF Core rejects with "A second operation was started on this context instance...". Inject `IDbContextFactory<PatisserieDb>` and create a context inside each load, so each query has its own instance.
- A product's price changed in the database, but a user who has had the tab open for an hour still sees the old price after navigating back to the cake list; why?With a circuit-scoped context the entity was tracked an hour ago, and a tracking query returns the already-tracked instance rather than overwriting it with the new row values. A fresh context per operation, or `AsNoTracking` for read-only lists, returns current data.
- A scoped DbContext on Interactive Server is created per HTTP request like in MVC.
- DbContext is safe to share between components because Blazor runs one thing at a time.
- Registering the DbContext as a singleton solves the concurrency error.
- IDbContextFactory returns the same context instance on every call.
- Contexts created from the factory are disposed automatically by DI.