简体   繁体   中英

Do I need to call context.dispose when adding the dbcontext with DI?

I have a ASP.NET CORE web API using EF. I'm wondering if I need to manually dispose my dbcontext. When adding your dbcontext with DI, it is my understanding that this gets added as a scoped service that recreates the context for each request.

I've registered it as a service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<FeedbackContext>();
}

And used in controller like this:

public Controller(FeedbackContext context)
{
    _context = context;
}

Do I need to dispose the context in my controller like this:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        _context.Dispose();
    }
    base.Dispose(disposing);
}

Or is this handled for me?

You do not need to call Dispose . ASP.NET Core will do that for you. Using AddDbContext , the context will be scoped to the request. All scoped objects will be disposed when the request finishes.

In fact, you can see this for yourself by overriding Dispose and putting a breakpoint inside it or logging something.

public class FeedbackContext : DbContext
{
    public override void Dispose()
    {
        base.Dispose();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM