How to Manage ObjectContext Per Request in ASP.NET

May 18, 2010

How to Manage ObjectContext Per Request in ASP.NET


We started a newHow to Manage ObjectContext Per Request in ASP.NET
project at work.
One of my guidelines
was to manage the
lifetime of the Entity
Framework
’s ObjectContext
as context per request.
Since I got some questions in the area I decided to explain how you
can achieve that.


Why to Use an ObjectContext Per Request?


In a previous post I wrote about this subject. The main issue
is that the context should be a short living object. Since
this is the case but we want to gain all the advantages of
using the context (which include lazy loading, change tracking and
more), I prefer to use a context per request in web applications.


How to Manage ObjectContext Per Request in ASP.NET?


When we want to use an ObjectContext per request in web applications
we need to find a centralized place which will hold the context during
the request. For our rescue comes the HttpContext class. The
HttpContext lives during the request and is dispose after it so its our
perfect candidate. We can use the Items collection that it holds in order
to keep the instance of our ObjectContext. One drawback of this is
that we need a dependency on System.Web library in order to use this class.
So how can we do that? we will create an helper class that will retrieve
the context when we need it. In the helper class we will use lazy loading
in order to create the context only when we need it. Here is a simple
example of how to do that:



public static class ContextHelper<T> where T : ObjectContext, new()
{
  #region Consts
 
  private const string ObjectContextKey = “ObjectContext”;
 
  #endregion
 
  #region Methods
 
  public static T GetCurrentContext()
  {
    HttpContext httpContext = HttpContext.Current;
    if (httpContext != null)
    {
      string contextTypeKey = ObjectContextKey + typeof(T).Name;
      if (httpContext.Items[contextTypeKey] == null)
      {
        httpContext.Items.Add(contextTypeKey, new T());
      }
      return httpContext.Items[contextTypeKey] as T;
    }
    throw new ApplicationException(“There is no Http Context available”);
  }
 
  #endregion
}

Summary


Lets wrap up, in web application my suggestion is to use an
ObjectContext per request. This will help us to have a short living
ObjectContext and to use its capabilities for change tracking and
other mechanisms. There are other solutions such as a static
context (don’t do that!) or context per business transaction but
as I wrote I prefer context per request.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

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=""> <strike> <strong>

3 comments

  1. Wes McClureMay 19, 2010 ב 8:39

    A better approach is to abstract the storage mechanism (HttpContext in this case) so it can be “injected” or configured. My best recommendation is to remove the static members above and use an IoC in your application to manage the lifestyle of the instance with instance members. Also, remove the usage of HttpContext and replace it with an instance member to store the context once opened.

    Castle Windsor has a PerWebRequest lifestyle that manages one instance of a service per request. This removes the need to worry about the HttpContext! No more dependency is needed to System.Web and even more important, if you want to use this in a console application, you can configure Windsor to manage the class as a singleton or another appropriate lifestyle. AOP FTW!

    I also find it useful to auto flush changes when a request successfully completes. This separates the aspect of persisting changes from the business logic manipulating the domain. This can be accomplished with an IHttpModule during end request.

    Reply
  2. Gil FinkMay 20, 2010 ב 7:48

    Hi Wes,
    Thank you for your important comment.
    As someone whi uses IoC containers in applications I must agree that its a better solution for this kind of problem. As I wrote in the post, this suggested solution is a simple one which can be applied very fast.

    Reply
  3. ccjreeoxoqf@gmail.comDecember 10, 2013 ב 19:54

    Thank you so much for the article. This approach is very useful and cleaner.

    Reply