Mats
Mats

Reputation: 109

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?

Upvotes: 7

Views: 4121

Answers (1)

Knelis
Knelis

Reputation: 7129

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();
    }
}

Upvotes: 12

Related Questions