Question

Is it considered a good practice to use a single ObjectContext per request? I read these objects should be short lived and are not extremely costly to instantiate but does this make the case appealing for one of them per request? If yes, are there any patterns that properly implement this?

Was it helpful?

Solution

Yes it is an accepted approach to have ObjectContext/DbContext with lifetimes per HttpRequest. Here's a sample I have provided in another answer.

Hoewever, it's better to leave these lifetime managements to an IoC library. Famous ones are Castle Windsor, Autofac.

Update:
To dispose your context, you can use Application_EndRequest method in Global.asax. The following code is not tested but you'll get the idea:

protected virtual void Application_EndRequest()
{
    var key = "MyDb_" + HttpContext.Current.GetHashCode().ToString("x")
                      + Thread.CurrentContext.ContextID.ToString();
    var context = HttpContext.Current.Items[key] as MyDbContext;

    if (context != null)
    {
        context.Dispose();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top