C#: Cannot access a disposed context instance
EF Core throws this when a DbContext is disposed, shared across threads, or captured by a task. Respect the scope and create one per unit of work.

Introduction & Quick Summary
An EF Core request fails with an exception that names the exact mistake:
System.ObjectDisposedException: Cannot access a disposed context instance.
A common cause of this error is disposing a context instance that was resolved
from dependency injection and then later trying to use the same context instance
elsewhere in your application. If you are calling Dispose() on the context, or
wrapping it in a using statement, make sure you are not doing so on a context
instance that was resolved from dependency injection.The DbContext existed, then its owner disposed it, and code kept using the reference. In a web request the usual owner is the DI scope, which ends when the request ends. In a background service it is often a using block that closed before an awaited task finished.
Where it comes from:
- A captured
DbContextused fromTask.Run,Task.WhenAll, or a timer after the request completed. - A singleton service that receives a scoped
DbContextin its constructor. using (var db = ...)around a context that DI already owns.- A Blazor Server component that keeps the injected context across awaits while the circuit recycles.
- Parallel queries sharing one context, which also produces
A second operation was started on this context instance.
Quick answer: keep DbContext scoped, never store it in a field of a longer-lived object, and create a new scope or a factory-created context for work that outlives a request.
Core Mechanics, Signatures & Reproducible Setup
AddDbContext<TContext> registers the context as scoped by default. The scope is created by the host: one per HTTP request, one per Blazor circuit, one per message in a worker. Dispose is called by the scope, which is why application code should not dispose it again.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Db")));
var app = builder.Build();
app.MapGet("/orders/{id}", async (int id, AppDbContext db) =>
await db.Orders.FindAsync(id) is Order order
? Results.Ok(order)
: Results.NotFound());A minimal reproduction starts work and returns before it finishes:
app.MapPost("/orders", async (AppDbContext db) =>
{
var order = new Order { Id = Guid.NewGuid() };
db.Orders.Add(order);
await db.SaveChangesAsync();
_ = Task.Run(async () =>
{
await Task.Delay(5000);
await db.SaveChangesAsync(); // scope is gone: ObjectDisposedException
});
return Results.Created($"/orders/{order.Id}", order);
});The related errors point at different mistakes:
| Exception | Meaning |
|---|---|
Cannot access a disposed context instance | context was disposed before this call |
A second operation was started on this context instance | concurrent use of one context |
Cannot resolve scoped service from root provider | singleton captured a scoped service |
No database provider has been configured | wrong registration, not a lifetime issue |
Key Comparison Table
| Registration | Lifetime | Safe for parallel work | Use |
|---|---|---|---|
AddDbContext | scoped | no | default for web requests |
AddDbContextFactory | factory per call | yes | background jobs, Blazor |
AddPooledDbContextFactory | pooled factory | yes | high-throughput workers |
AddDbContext as transient | new per resolution | per instance only | rare, memory-heavy |
AddDbContext as singleton | process | no | never with EF Core |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Read the stack for the disposing frame
The DbContext constructor stack shows where it was created, and in ASP.NET Core logs the exception after Request finished means the scope ended first.
app.Use(async (context, next) =>
{
try
{
await next();
}
finally
{
// logging here runs before the scope is disposed, which helps ordering
app.Logger.LogInformation("scope ending for {Path}", context.Request.Path);
}
});Request-scoped services are disposed after the middleware pipeline completes, so any fire-and-forget work started inside the pipeline races that disposal.
2. Background work with a scope factory
A hosted service or queue consumer must create its own scope per unit of work. Injecting a DbContext into the constructor of a singleton is the mistake that produces this error on the first message after startup.
public sealed class OrderWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopes;
public OrderWorker(IServiceScopeFactory scopes) => _scopes = scopes;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var pending = await db.Orders.Where(o => o.ProcessedAt == null).ToListAsync(stoppingToken);
foreach (var order in pending)
order.ProcessedAt = DateTime.UtcNow;
await db.SaveChangesAsync(stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}The scope lives for one iteration, so the context is disposed exactly when the unit of work ends.
3. IDbContextFactory for parallel or long-lived components
Blazor Server components and parallel loops need a context that is not tied to the caller's scope. A factory hands out a fresh instance on demand.
builder.Services.AddDbContextFactory<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Db")));
public sealed class ReportService(IDbContextFactory<AppDbContext> factory)
{
public async Task<int[]> CountsAsync(CancellationToken ct)
{
await using var db = await factory.CreateDbContextAsync(ct);
return await db.Orders.GroupBy(o => o.Status).Select(g => g.Count()).ToArrayAsync(ct);
}
}AddPooledDbContextFactory reuses context instances internally and resets state between leases. It is faster under load, and it is still one context per lease, so concurrency rules are unchanged.
4. One context per parallel task
Even with a correctly scoped context, Task.WhenAll over the same instance fails. EF Core tracks entities in a single graph and is not thread-safe.
await using var db1 = await factory.CreateDbContextAsync();
await using var db2 = await factory.CreateDbContextAsync();
await Task.WhenAll(
db1.Orders.Where(o => o.Status == "new").ToListAsync(),
db2.Customers.CountAsync());Splitting the work across contexts is safe; combining the results afterwards is plain in-memory code. Running the queries sequentially on one context is the simpler alternative when the load is low.
5. Blazor Server component lifetime
A circuit outlives a single render, and the injected context is scoped to the circuit. Long-running work started from a component can outlive a reconnect and hit a disposed context.
@inject IDbContextFactory<AppDbContext> Factory
@code {
private List<Order> orders = new();
protected override async Task OnInitializedAsync()
{
await using var db = await Factory.CreateDbContextAsync();
orders = await db.Orders.AsNoTracking().ToListAsync();
}
}Using the factory keeps component code independent of the circuit lifetime, which is what makes reconnection reliable.
6. Tests and using blocks
In tests the context is created manually, so the lifetime is explicit and the bug is usually a shared fixture that was disposed by one test while another still used it.
public sealed class OrderTests : IAsyncLifetime
{
private AppDbContext _db = null!;
public async Task InitializeAsync()
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite("DataSource=:memory:").Options;
_db = new AppDbContext(options);
await _db.Database.EnsureCreatedAsync();
}
public async Task DisposeAsync() => await _db.DisposeAsync();
}One context per test class is fine when tests run sequentially. Parallel test execution needs one context per test, created through a factory or a fresh fixture.
Common Compilation/Runtime Mistakes & Version Gotchas
- Registering the context as a singleton. The container throws at startup with a scope-validation message, and disabling validation moves the failure to runtime.
usingon an injected context. The scope disposes it again, which is harmless, but the first disposal is what breaks later code in the same request.- Fire-and-forget with
Task.Run. The task has no scope and noHttpContext; both are invalid after the response completes. Use a queue or a hosted service. - Version differences. Pooled factories,
AddDbContextFactoryoverloads, and scope validation behaviour changed across EF Core majors; check the version in use before copying registration code.
| Symptom | Cause | Fix |
|---|---|---|
| fails only under load | parallel use of one context | one context per task |
| fails after a few minutes idle | scope ended, timer still running | scope inside the timer callback |
| fails on first request after deploy | singleton captured scoped context | inject the factory |
| works in tests, fails in app | manual disposal in tests | mirror DI lifetimes |
When the failing object is data rather than lifetime, paste the serialized payload into the JSON formatter to confirm the shape, and use the text diff tool to compare two service registrations that behave differently.
The lifetime rules are documented in DbContext configuration, including the difference between AddDbContext, AddDbContextFactory, and pooled factories, and the general scope model behind this error is described in the .NET dependency injection guidelines.
Official references
primary documentationThe C# documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# CS0246: The type or namespace name could not be found
CS0246 is a compile-time resolution failure: a missing using, package, target framework, or an unrestored project. Trace it backward from the symbol.
C#: NullReferenceException: Object reference not set
The message never names the null. Read the stack trace, enable nullable reference types, and use null-conditional access instead of guessing.
.NET: The framework 'Microsoft.NETCore.App' was not found
A framework-dependent app asks for a runtime major that is absent. Install the matching runtime or publish self-contained, and match Docker tags.
C# CS7036: no argument given that corresponds to the required parameter
CS7036 means the chosen constructor or method expects an argument the caller skipped. Match the signature instead of casting or adding a null default.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.