Entity Framework - closure of Object Contexts
Asked Answered
S

3

5

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?

Superabundant answered 4/10, 2012 at 14:22 Comment(1)
+1 for caring what EF is ACTUALLY doing!Hullo
Y
4

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?

Yuki answered 4/10, 2012 at 14:37 Comment(0)
E
2

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.

Envoy answered 4/10, 2012 at 14:30 Comment(0)
H
2

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...

Haitian answered 4/10, 2012 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.