DCSIMG
How to Manage ObjectContext Per Request in ASP.NET - 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

How to Manage ObjectContext Per Request in ASP.NET

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.

Comments

Twitter Trackbacks for How to Manage ObjectContext Per Request in ASP.NET - Gil Fink on .Net [microsoft.co.il] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 How to Manage ObjectContext Per Request in ASP.NET - Gil Fink on .Net         [microsoft.co.il]        on Topsy.com

# May 18, 2010 3:54 PM

Wes McClure said:

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.

# May 19, 2010 8:39 AM

Gil Fink said:

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.

# May 20, 2010 7:48 AM