Most ASP.NET Core applications access a database through Entity Framework Core’s DbContext. For a conventional web API, creating one context per HTTP request is usually the correct and sufficient design. The situation changes when an application also performs background processing, runs parallel operations, serves Blazor Server circuits, or needs multiple independent units of work inside one request.
This article solves a practical problem: a background order processor receives a single injected DbContext, processes several messages, and occasionally throws “A second operation was started on this context instance before a previous operation completed.” The answer is not to make the context a singleton. The safer solution is to create a context for each unit of work.
Why a DbContext should be short-lived
A DbContext is not a database connection. It coordinates change tracking, query execution, and a unit of work. EF Core contexts are not thread-safe and should not be accessed concurrently by multiple operations.
In ASP.NET Core, AddDbContext registers a context with a scoped lifetime by default. This normally works well because an HTTP request commonly represents one unit of work. Problems arise when a singleton service consumes that scoped context directly.
builder.Services.AddDbContext<OrderDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddSingleton<OrderWorker>();If OrderWorker receives OrderDbContext through its constructor, the lifetimes are incompatible. In development, dependency injection validation may report the problem. If it is not detected, one context can remain alive across multiple messages and carry state far beyond the intended unit of work.
The real problem: parallel order processing
Consider a worker that processes messages from a queue:
public sealed class OrderWorker
{
private readonly OrderDbContext _db;
public OrderWorker(OrderDbContext db)
{
_db = db;
}
public async Task ProcessAsync(OrderMessage message)
{
var order = await _db.Orders.FindAsync(message.OrderId);
order!.Status = "Processed";
await _db.SaveChangesAsync();
}
}This code may appear safe when called sequentially. However, if the same worker processes multiple messages concurrently, both operations can reach the same context. The change tracker may also retain entities longer than necessary, while the context lifetime no longer matches the business operation.
Use IDbContextFactory for explicit units of work
IDbContextFactory<TContext> creates a context when application code needs one. The factory is managed by dependency injection, but contexts created by the factory must be disposed by the calling code.
builder.Services.AddDbContextFactory<OrderDbContext>(options =>
options.UseSqlServer(connectionString));
public sealed class OrderWorker
{
private readonly IDbContextFactory<OrderDbContext> _factory;
public OrderWorker(IDbContextFactory<OrderDbContext> factory)
{
_factory = factory;
}
public async Task ProcessAsync(
OrderMessage message,
CancellationToken cancellationToken)
{
await using var db = await _factory.CreateDbContextAsync(cancellationToken);
var order = await db.Orders
.SingleOrDefaultAsync(x => x.Id == message.OrderId, cancellationToken);
if (order is null)
return;
order.Status = "Processed";
order.ProcessedAtUtc = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
}
}Each message now receives an independent context. When processing finishes, the context is disposed and its change tracker is released. Parallel operations no longer share context state.
Multiple units of work in one request
A factory is also useful when one HTTP request contains separate units of work. For example, a reporting endpoint might read operational data and then create an audit record using a separate context. This keeps tracking state isolated between the two operations.
Using a factory does not mean creating a new context for every individual query without a reason. Define the unit-of-work boundary first. Operations that must participate in the same transaction should use the same context and transaction scope.
When should context pooling be used?
AddPooledDbContextFactory and AddDbContextPool reuse disposed context instances. This can reduce the cost of repeatedly creating contexts and initializing their internal services. Context pooling is different from database connection pooling: connection pooling is handled by the ADO.NET provider, while context pooling is handled by EF Core.
builder.Services.AddPooledDbContextFactory<OrderDbContext>(
options => options.UseSqlServer(connectionString),
poolSize: 128);The pool size should reflect the application’s concurrency, memory limits, and database capacity. A full pool does not mean the application can no longer work; EF Core can create non-retained instances when necessary. Pooling is an optimization, not a replacement for capacity planning.
The tenant-state trap with pooled contexts
A pooled context may be reused by different requests or units of work. For that reason, request-specific, user-specific, or tenant-specific state must not be configured as if the context were created only once for a single request. In particular, OnConfiguring is not a suitable place for state that must change between pooled uses.
In a multi-tenant application, a tenant identifier used by a global query filter must be assigned deliberately for each unit of work. The tenant must come from trusted authentication or authorization data, not from an unvalidated query-string value.
Choosing the appropriate registration
| Scenario | Recommended approach | Reason |
|---|---|---|
| Standard MVC or API request | AddDbContext | A request-scoped unit of work is usually sufficient. |
| Background service or queue consumer | IDbContextFactory | Each message can receive a controlled context. |
| High context creation overhead | AddPooledDbContextFactory | Context instances can be reused. |
| Parallel operations | One context per operation | A non-thread-safe context is never shared concurrently. |
Implementation checklist
- Do not register a
DbContextas a singleton. - Do not run parallel queries on the same context instance.
- Dispose factory-created contexts with
usingorawait using. - Use an explicit scope or a context factory when background work needs scoped dependencies.
- Enable pooling only after measuring the real workload.
- Do not leave request, user, or tenant state uncontrolled inside pooled contexts.
- Await asynchronous EF Core operations before starting another operation on the same context.
In practice, many EF Core lifetime problems are not caused by slow SQL. They are caused by a mismatch between the context lifetime and the business unit of work. Scoped contexts remain a good default for ordinary web requests. For background jobs, parallel work, and application flows with different lifetimes, IDbContextFactory provides a safer boundary. Pooling can then be added as a measured optimization, provided that reusable context state is handled correctly.
Sources
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection
- https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew
0 Comments