Search code examples
asp.netentity-frameworkasp.net-identityowindbcontext

Should I dispose given ApplicationDbContext in the End_Request event handler?


I have Asp.Net Webforms application with entity framework. Application is built on the default web application from Visual Studio.

Application is configured so that ApplicationDbContext is created per Owin Context (per request). I am not closing DbContext after every DB query because that way I won't leverage all the caching that EF provides

So I use given DbContext returned from current Owin Context. But I don't see any piece of code that is disposing given DbContext. Should I dispose given DbContext in the End_Request event handler? Or it is handled automagically? (I guess not)


Solution

  • DbContext instances should be disposed of (but you'll probably be OK if they're not) DbContext implements IDisposable. Its instances should therefore be disposed of as soon as they're not needed anymore. In practice however, and unless you choose to explicitly manage the database connection or transaction that the DbContext uses, not calling DbContext.Dispose() won't cause any issues

    as Diego Vega, a EF team member, explains Do I always have to call Dispose() on my DbContext objects? Nope

    From my experience I can add this: In the past I never worried about disposing the dbcontext and i never had any kind of problems. Lately I don't create it manually but i let my DI container instantiate it for me and dispose it when is time to dispose.