Entity Framework Context Lifetime Best Practices

February 7, 2010

Entity Framework Context Lifetime Best Practices

In this post I’mEntity Framework Context Lifetime Best Practices
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.

DotNetKicks Image
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

8 comments

  1. AchuFebruary 10, 2010 ב 20:01

    Good article. I wish everybody blogs their Rules of Thumb.

    I beleive once we have Self Tracking Entities in place the context life time issue will be solved.

    what feature’s of EF 4 packed in VS 2010 RC?

    Thanks,
    Achu.

    Reply
  2. GregJFFebruary 11, 2015 ב 0:15

    This comment has danger:
    “Web applications – use the context per request.”
    If you have more 150 concurrent web request and you keep open the DBContext per web request, then you Connection pool is going to be exhausted. and under load you will suffer unexpected timeout issues.
    You should use the using block to break up the logical read/writes so that when the DBContext is dispose of the connection is returned to the Connection Pool. The Connection Pool is configurable on the Connection String and the pool itself is a OLE DB object.

    Reply
    1. Gil Fink
      Gil FinkOctober 9, 2015 ב 15:43

      @Greg,
      Yep. If your server is under load and you have a lot of heavy things going on in your requests then having open DbContexts for each request my exhaust the connection pool. This is why you should strive that your transactions will be short and async if possible.

      Pay attention that this post is from 2010 and since then a lot has changed in EF. Now you can use async transactions to free your threads and much more.

      Reply
  3. Aaron LawrenceOctober 9, 2015 ב 3:10

    What do you mean with
    “holds all the server transaction” ?

    Reply
    1. Gil Fink
      Gil FinkOctober 9, 2015 ב 15:39

      @Aaron,
      My meaning is that in web applications each request can be looked upon as a whole transaction against the server (even if during the request you are doing tons of stuff). The client expect only one response back and it doesn’t need to know what’s going on under the hood during the request.

      Reply
  4. FaridDecember 15, 2015 ב 10:48

    Nice article but I’m still confused, what if so many instance of a same WPF application runs simultaneously and they are connected to only one sqlServer, is it still good idea to use context per form? or what if the application terminates unexpectedly ( crashing for example) the the connection to server wont be closed.

    Reply
  5. Pingback: c# - Managing per form ObjectContext lifetime - CSS PHP

  6. ShalevNovember 28, 2017 ב 17:41

    Hi.
    You assume desktop applications are form based (AKA MDI application). Most applications today are more similar to visual studio. There is usually a Tree Navigator that may possibly display all items.
    What would be your suggestion regarding the Context in this case ?

    Reply