Entity Framework and calling context.dispose()

In fact this is two questions in one:

  1. When should I Dispose() of a context?
  2. What should be the lifespan of my context?

Answers:

  1. Never 1. using is an implicit Dispose() in a try-finally block. A separate Dispose statement can be missed when an exception occurs earlier. Also, in most common cases, not calling Dispose at all (either implicitly or explicitly) isn’t harmful.

  2. See e.g. Entity Framework 4 – lifespan/scope of context in a winform application. In short: lifespan should be “short”, static context is bad.


1 As some people commented, an exception to this rule is when a context is part of a component that implements IDisposable itself and shares its life cycle. In that case you’d call context.Dispose() in the Dispose method of the component.

Leave a Comment