2

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)

ino_fleg
  • 87
  • 1
  • 7
  • This post can help you http://stackoverflow.com/questions/15666824/entity-framework-and-context-dispose – Ghini Antonio Apr 30 '17 at 12:08
  • 1
    Ok, so it seems that I should not worry about closing a DbContext that I got from Http.Context.Current.Get(), but somehow it seems weird to me and I am used to dispose things. Because I saw at MVC project that they disposed DbContext, in the Dispose method of the Controller. – ino_fleg Apr 30 '17 at 14:35

1 Answers1

2

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.

Ghini Antonio
  • 2,992
  • 2
  • 25
  • 48