Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Mats Avatar asked Mar 08 '18 08:03

Mats


1 Answers

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();
    }
}
like image 104
Knelis Avatar answered Nov 14 '22 22:11

Knelis