How to Manage ObjectContext Per Request in ASP.NET
We started a new
project at work.
One of my guidelines
was to manage the
lifetime of the Entity
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()
private const string ObjectContextKey = “ObjectContext”;
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”);
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.