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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With