Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Object Context per request in ASP.NET? [closed]

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?

like image 666
kfc Avatar asked Feb 12 '26 23:02

kfc


1 Answers

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();
    }
}
like image 179
Kamyar Avatar answered Feb 14 '26 15:02

Kamyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!