Entity Framework Context Lifetime Best Practices
Entity Framework Context Lifetime Best Practices
In this post I’m
going to write
about one of the
major decisions
that you need to
take when you use
ORM tools like Entity Framework.
This decision is the context lifetime.
The Problem
Context lifetime is a very crucial decision to make when we
use ORMs. Since the context is acting as an entity cache (it holds
references to all the loaded entities for change tracking and
lazy loading purpose), it may grow very fast in memory consumption.
Also this behavior can cause a memory leak because if we don’t
dispose our context it will have references to all the loaded entities
and by that they will never be collected by the Garbage Collection.
Another problem that raise its ugly head is keeping a context lifetime
to long or to short. If we dispose the context after every database
manipulation or query we won’t enjoy the all the features it holds
(for example change tracking).
For example the following code disposes the context very fast and
shows the problem I talk about:
using (var context = new SchoolEntities())
{
context.AddToDepartments(department);
context.SaveChanges();
}
On the other hand, keeping a long running context is also bad practice.
Sometimes I see developers that use the context as a singleton in their
system. This is very bad since as I wrote it can cause a memory leak.
Also it is bad habit because you will have transactions for longer time
than you should have them. Business transactions and connection
management should be used in very short bursts and only as they are
needed.
My Rules of Thumb
- Web applications – use the context per request. Since in web
applications we deal with requests that are very short but holds
all the server transaction then they are the proper duration for
the context to live in. We will enjoy all the functionality of the
context and it won’t hang up very long.
- Smart clients (Win Forms/WPF etc) – use a context per form.
Since we don’t want to have the context as a singleton for our
application we will dispose it when we move from one form to
another. In this way we will gain a lot of the context’s abilities
and won’t suffer from the implications of long running contexts.
Summery
Managing context lifetime is very crucial decision that we need to take
at the starting of every project. My rules of thumb is context per
request and context per form lifetimes.