How to Manage ObjectContext Per Request in ASP.NET
Join the DZone community and get the full member experience.Join For Free
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 lading, 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.
Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Logging Best Practices Revisited [Video]
How To Use an Automatic Sequence Diagram Generator
21 Hidden Careers in the AI Revolution: Driving Change in the Tech Industry
Build a Simple Chat Server With gRPC in .Net Core