Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readC#
#C##.NET#EF Core#Dependency Injection
A C# DbContext crate closed at a cyan scope gate, an amber background task reaching for it

Introduction & Quick Summary

An EF Core request fails with an exception that names the exact mistake:

code
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 DbContext used from Task.Run, Task.WhenAll, or a timer after the request completed.
  • A singleton service that receives a scoped DbContext in 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.

csharp
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:

csharp
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:

ExceptionMeaning
Cannot access a disposed context instancecontext was disposed before this call
A second operation was started on this context instanceconcurrent use of one context
Cannot resolve scoped service from root providersingleton captured a scoped service
No database provider has been configuredwrong registration, not a lifetime issue

Key Comparison Table

RegistrationLifetimeSafe for parallel workUse
AddDbContextscopednodefault for web requests
AddDbContextFactoryfactory per callyesbackground jobs, Blazor
AddPooledDbContextFactorypooled factoryyeshigh-throughput workers
AddDbContext as transientnew per resolutionper instance onlyrare, memory-heavy
AddDbContext as singletonprocessnonever 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.

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

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

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

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

csharp
@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.

csharp
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.
  • using on 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 no HttpContext; both are invalid after the response completes. Use a queue or a hosted service.
  • Version differences. Pooled factories, AddDbContextFactory overloads, and scope validation behaviour changed across EF Core majors; check the version in use before copying registration code.
SymptomCauseFix
fails only under loadparallel use of one contextone context per task
fails after a few minutes idlescope ended, timer still runningscope inside the timer callback
fails on first request after deploysingleton captured scoped contextinject the factory
works in tests, fails in appmanual disposal in testsmirror 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 documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.