DCSIMG
Entity Framework Context Lifetime Best Practices - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Entity Framework Context Lifetime Best Practices

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

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# February 7, 2010 9:46 AM

Achu said:

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.

# February 10, 2010 8:01 PM

Twitter Trackbacks for Entity Framework Context Lifetime Best Practices - Gil Fink on .Net [microsoft.co.il] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Entity Framework Context Lifetime Best Practices - Gil Fink on .Net         [microsoft.co.il]        on Topsy.com

# May 3, 2010 5:02 PM

Gil Fink on .Net said:

How to Manage ObjectContext Per Request in ASP.NET We started a new project at work. One of my guidelines

# May 18, 2010 2:54 PM

Rolling my own ObjectContext and Interface « Cesar Meraz said:

Pingback from  Rolling my own ObjectContext and Interface  « Cesar Meraz

# September 19, 2010 6:16 PM

Does Entity Framework have some sort of context caching? - Programmers Goodies said:

Pingback from  Does Entity Framework have some sort of context caching? - Programmers Goodies

# October 15, 2011 1:01 AM

Do any of these Entity Framework recommendations conflict with each other? | DIGG LINK said:

Pingback from  Do any of these Entity Framework recommendations conflict with each other? | DIGG LINK

# November 19, 2011 12:59 PM