Introduction
Many Entity Framework Core failures are not caused directly by a LINQ expression or an incorrect database schema. In many cases, the root cause is an incorrectly configured DbContext lifetime, a context that is kept alive for too long, or a single context being used by multiple operations at the same time.
This lesson examines DbContext lifetime management in EF Core 10 and .NET 10 applications. You will see why Singleton registration is unsafe, how scoped lifetime normally works in ASP.NET Core, and when IDbContextFactory<TContext> is the better choice for background work and independent concurrent operations.
By the end of the lesson, you will be able to diagnose disposed contexts, concurrent-use failures, shared-context bugs, and dependency injection lifetime mismatches by starting from the runtime symptoms.
1. Why should DbContext be short-lived?
DbContext is more than a simple database connection wrapper. It tracks entity instances, maintains an identity map, detects changes, manages query state, and determines which SQL operations should be generated when SaveChanges is called.
As the lifetime of a context increases, several risks become more likely:
- The change tracker accumulates more entities than necessary.
- Previously loaded values remain in memory and stale state may be used.
- Different instances of the same entity can create tracking conflicts.
- Memory usage and the cost of
SaveChangescan increase. - Concurrent operations can fail because the same context is accessed simultaneously.
The common recommendation for ASP.NET Core web applications is to use one scoped context per HTTP request. The request performs its unit of work, and the dependency injection container disposes the context when the request scope ends.
2. Why is Singleton DbContext incorrect?
The following registration may appear convenient because every component can use the same context:
builder.Services.AddSingleton<AppDbContext>();However, this creates serious risks in production applications. A Singleton remains alive until the application shuts down. Since many HTTP requests can execute at the same time, requests from different users may access the same DbContext instance.
For example, one request may update an order while another request queries products through the same context. The change tracker, connection state, or active operation of one request can interfere with the other. DbContext is not thread-safe and must not be accessed concurrently from multiple threads.
Typical consequences of Singleton registration include:
- Corrupted or stale state: Previously loaded entities remain tracked.
- Tracking conflicts: Two entity instances with the same key may be attached to one context.
- Concurrency exceptions: A new operation starts before the previous operation has completed.
- Data isolation risks: State from one request can accidentally influence another request.
- Performance degradation: The long-lived change tracker continues to grow.
3. The correct default: Scoped lifetime
In ASP.NET Core, AddDbContext registers a context with scoped lifetime by default:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
This creates one AppDbContext instance per dependency injection scope. In a typical Web API, each HTTP request has its own scope, so the practical result is one context per request.
A service can receive the context through constructor injection:
public sealed class OrderService(AppDbContext db)
{
public async Task<Order?> GetAsync(
int id,
CancellationToken cancellationToken)
{
return await db.Orders
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
}
}
This service should not be registered as a Singleton. Injecting a scoped context into another scoped service is appropriate, while injecting it into a Singleton creates a lifetime mismatch.
Incorrect service registration
builder.Services.AddSingleton<OrderService>();
builder.Services.AddDbContext<AppDbContext>();This can cause the service to retain a scoped context for too long or cause the dependency injection container to reject the dependency. The service lifetime should match the context lifetime:
builder.Services.AddScoped<OrderService>();
builder.Services.AddDbContext<AppDbContext>();4. The request-per-context approach
A context per request is the most common unit-of-work pattern in web applications. A controller or endpoint can perform several queries and updates, call SaveChangesAsync, and allow the request scope to dispose the context when the operation ends.
app.MapPut("/orders/{id:int}", async (
int id,
UpdateOrderRequest request,
AppDbContext db,
CancellationToken cancellationToken) =>
{
var order = await db.Orders
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
if (order is null)
return Results.NotFound();
order.Status = request.Status;
await db.SaveChangesAsync(cancellationToken);
return Results.NoContent();
});
Tracking is intentional here. Since the order was loaded by this context, EF Core can detect the change to Status and generate the appropriate update. For read-only queries, AsNoTracking can reduce change-tracking overhead.
5. The shared-context parallel operation problem
The following code is incorrect:
public async Task<DashboardData> LoadDashboardAsync(
CancellationToken cancellationToken)
{
var ordersTask = db.Orders.CountAsync(cancellationToken);
var customersTask = db.Customers.CountAsync(cancellationToken);
await Task.WhenAll(ordersTask, customersTask);
return new DashboardData(
ordersTask.Result,
customersTask.Result);
}
Both queries are started on the same DbContext at the same time. EF Core does not support parallel operations on one context instance. A common error explains that a second operation was started before the previous operation completed.
The simplest correction is to execute the queries sequentially:
public async Task<DashboardData> LoadDashboardAsync(
CancellationToken cancellationToken)
{
var orderCount = await db.Orders.CountAsync(cancellationToken);
var customerCount = await db.Customers.CountAsync(cancellationToken);
return new DashboardData(orderCount, customerCount);
}
If parallel execution is genuinely required, each operation must use a separate context. This is where IDbContextFactory becomes useful.
6. Using IDbContextFactory
A context factory is useful for background services, queue consumers, scheduled jobs, and scenarios involving multiple independent database operations. Register it as follows:
builder.Services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
The factory creates a new context for each call. The code that creates the context is responsible for disposing it:
public sealed class DashboardService(
IDbContextFactory<AppDbContext> factory)
{
public async Task<DashboardData> LoadAsync(
CancellationToken cancellationToken)
{
await using var ordersDb =
await factory.CreateDbContextAsync(cancellationToken);
await using var customersDb =
await factory.CreateDbContextAsync(cancellationToken);
var ordersTask = ordersDb.Orders.CountAsync(cancellationToken);
var customersTask = customersDb.Customers.CountAsync(cancellationToken);
await Task.WhenAll(ordersTask, customersTask);
return new DashboardData(
await ordersTask,
await customersTask);
}
}
The queries now run on different context instances, so they do not conflict through shared context state. However, creating a context for every operation is not automatically better. Connection-pool capacity, database limits, and actual query cost should be measured before introducing parallelism.
7. The disposed-context problem
A context created inside a using block must not be returned for use outside that block:
private AppDbContext CreateContext()
{
using var db = new AppDbContext(_options);
return db;
}
When this method returns, the context has already been disposed. A later query can throw ObjectDisposedException. The correct approach is to complete the operation within the same scope or method:
public async Task<int> CountOrdersAsync(
CancellationToken cancellationToken)
{
await using var db = await factory.CreateDbContextAsync(cancellationToken);
return await db.Orders.CountAsync(cancellationToken);
}
A similar problem occurs when a request-scoped context is captured by a background task. After the request ends, the context may already be disposed. Background work should create its own scope or use a factory.
8. Correct usage inside BackgroundService
A BackgroundService is effectively a long-lived service. A scoped context should not be injected directly into it. Instead, use a factory:
public sealed class OrderWorker(
IDbContextFactory<AppDbContext> factory,
ILogger<OrderWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await using var db =
await factory.CreateDbContextAsync(stoppingToken);
var pendingOrders = await db.Orders
.Where(x => x.Status == OrderStatus.Pending)
.Take(50)
.ToListAsync(stoppingToken);
foreach (var order in pendingOrders)
order.Status = OrderStatus.Processing;
await db.SaveChangesAsync(stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
}
Creating a new context for each loop prevents tracking state from one iteration from leaking into the next iteration.
9. A diagnosis checklist
- Check how the context is registered in dependency injection.
- Inspect the lifetime of every service that receives the context.
- Search for parallel tasks that use the same context instance.
- Await every asynchronous EF Core operation immediately.
- Check whether the context is being used after a
usingblock ends. - Use a scope or factory for long-running work instead of retaining a request context.
- Verify that Singleton services do not receive scoped contexts through their constructors.
10. Common mistakes
- Registering DbContext as Singleton: Avoid this because the context is stateful and not thread-safe.
- Keeping one context for an entire worker lifetime: This causes long-lived tracking and stale-state problems.
- Using Task.WhenAll with one context: Use separate contexts or execute operations sequentially.
- Starting another query before awaiting the previous one: Complete each EF Core async operation before reusing the context.
- Failing to dispose factory-created contexts: Use
await usingor explicit disposal. - Creating unnecessary contexts: A scoped context per request is sufficient when no concurrency is required.
Short Practice Exercise
In the following scenario, ReportService is registered as a Singleton and receives AppDbContext through constructor injection:
builder.Services.AddSingleton<ReportService>();
builder.Services.AddDbContext<AppDbContext>();Your tasks are:
- Explain why this registration is incorrect.
- Write the correct registration for a service used during a web request.
- Design a factory-based solution if the service is used by a
BackgroundService. - Run two count queries without executing them concurrently on the same context.
- Intentionally execute a query on a disposed context and explain the resulting exception.
The expected basic solution is to use AddDbContext with scoped services for normal request processing, and AddDbContextFactory for long-lived or independently concurrent operations.
Conclusion
DbContext lifetime directly affects the correctness and performance of an EF Core application. Singleton registration can lead to shared state, tracking conflicts, corrupted behavior, and concurrency failures.
For web applications, the safest default is a scoped context per request. For background services, queue consumers, and independent parallel operations, create short-lived contexts through IDbContextFactory. Never start a new operation on a context before the previous asynchronous operation has completed.
With these principles, you can move beyond merely suppressing error messages and analyze the real cause of a failure in terms of lifetime, scope, disposal, tracking, and thread usage.