Cannot access a disposed context instance 🟪 .NET

ObjectDisposedException: Cannot access a disposed context instance

Code used a DbContext after its scope ended — usually async void, fire-and-forget tasks, or capturing a scoped context in a singleton/background thread.

Seen on: .NET

Meaning

The request scope disposes the context when the request finishes. Work continuing after that (unawaited tasks, events, background threads) fails.

Common causes

  • async void or un-awaited Task using the context
  • Context captured by a singleton/hosted service
  • Lazy-loading navigation after the request ended

⚡ Quick fix

  1. Await all work within the request
  2. Use IServiceScopeFactory/IDbContextFactory in background work
  3. Materialise data before returning

Detailed fix by platform

C#

  1. csharp
    using var scope = scopeFactory.CreateScope();
    var db = scope.ServiceProvider.GetRequiredService<AppDb>();
    await db.SaveChangesAsync();

How to diagnose

  1. Timing — After the request?
  2. Lifetime — Who holds the context?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.