You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Entity Framework Core与.NET Core Web API:已释放对象访问错误排查

Troubleshooting "Cannot access a disposed object: PTEAContext" in EF Core & .NET Web API

Let’s break down this common EF Core issue and walk through the most likely fixes, based on your code and the error context.

The core problem here is that your PTEAContext instance is being disposed (cleaned up by the dependency injection container) before your code finishes using it. Even though your EfRepository looks correctly injected, let’s rule out the most common pitfalls:

1. Verify Your Context’s DI Lifecycle Configuration

First, double-check how you’re registering PTEAContext in your Program.cs (or Startup.cs for older .NET versions). EF Core contexts are meant to be registered as Scoped (one instance per HTTP request) in web apps.

If you accidentally registered it as Transient or Singleton, you’ll run into disposal issues:

  • Singleton: The context might get disposed unexpectedly, or hold onto resources longer than intended.
  • Transient: Multiple instances might be created, and one could be disposed while another part of your code still references it.

Correct Scoped registration example:

services.AddDbContext<PTEAContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("YourConnectionString")));

This is the default behavior for AddDbContext, so if you didn’t change it, this is probably fine—but it’s worth confirming.

2. Check for Manual Context Disposal or Instantiation

Search your entire codebase for any place where you:

  • Manually call _dbContext.Dispose()
  • Use a using block to create a context directly (e.g., using(var context = new PTEAContext()))

Your EfRepository doesn’t do this, but if other services or controllers are manually creating/disposing contexts, those instances will get cleaned up before async operations finish, leading to this error. Always let the DI container manage context lifecycle.

3. Fix "Fire-and-Forget" Async Calls

This is the #1 cause of this error in Web APIs. If you call an async method like AddAsync without awaiting it, the HTTP request will complete, and the DI container will dispose the context before the async operation finishes.

Wrong Example (Controller Code):

[HttpPost]
public IActionResult AddUser(Users user)
{
    _efRepository.AddAsync(user); // No await—request ends, context gets disposed
    return Ok();
}

Correct Example:

[HttpPost]
public async Task<IActionResult> AddUser(Users user)
{
    var addedUser = await _efRepository.AddAsync(user);
    return Ok(addedUser);
}

Make sure every async method call in your controllers, services, and repository consumers is properly awaited.

4. Check for Long-Running Operations Holding Context References

If you have background tasks, scheduled jobs, or long-running processes that use PTEAContext, they can’t rely on the Scoped context tied to an HTTP request. Once the request ends, the context is disposed, but the background task might still be running.

For background work, create a new scope to get a fresh context instance:

using(var scope = _serviceProvider.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<PTEAContext>();
    // Use context here—this instance will be disposed when the scope ends
}

5. Ensure Deferred Queries Are Executed Within Context Lifecycle

Your ApplySpecification returns an IQueryable<T>, which uses deferred execution. If you return this IQueryable from your repository and try to enumerate it (e.g., with ToList() or in a foreach loop) after the context is disposed, you’ll hit this error.

Your ListAsync and CountAsync methods correctly execute the query with ToListAsync() and CountAsync()—good. Just make sure any other uses of ApplySpecification also immediately execute the query within the context’s lifecycle.

Next Steps to Debug

  1. Start by auditing your controller code that calls AddAsync—this is where the error is triggered, so confirm you’re awaiting the call.
  2. If that checks out, verify your PTEAContext registration in Program.cs.
  3. Search your codebase for any manual new PTEAContext() or Dispose() calls.
  4. If you have background tasks, confirm they’re handling context scoping correctly.

Content of the question comes from Stack Exchange, asked by Prince Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:34:24