Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - closure of Object Contexts

After using EFProfiler (absolutely fantastic tool BTW!) for profiling a few of our Entity Framework applications, it seems that, in most cases, all of the Object Contexts are not closed.

For example, after running it locally, EF Profiler told me that there were 326 Object Context's opened, yet only 1 was closed?

So my question is, should I worry about this? Or is it self-contained within Entity Framework?

like image 238
mattytommo Avatar asked Oct 04 '12 14:10

mattytommo


3 Answers

If you're not using an IoC container is there anyway you can close the ObjectContexts manually after each request, for example in the End Request of your Global.asax, thereby simulating a "per request" lifestyle for your contexts?

like image 69
JonKers Avatar answered Oct 12 '22 11:10

JonKers


ObjectContexts will be disposed eventually if your application is not holding onto them explicitly, but in general, you should try to dispose them deterministically as soon as possible after you are done with them. In most cases, they will hold onto database connections until they are disposed. In my current web application, we use an IoC container (Autofac) to ensure that any ObjectContext opened during a request is disposed at the end of the request, and does not have to wait for garbage collection.

like image 42
jlew Avatar answered Oct 12 '22 10:10

jlew


I suggest you do worry about it and try to fix the issue as Object Contexts are pretty "bulky". If you have too many of them your application may eventually end up using more memory than it needs to and IIS will be restarting your application more frequently then...

like image 39
Sidharth Mudgal Avatar answered Oct 12 '22 11:10

Sidharth Mudgal