문제

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?

도움이 되었습니까?

해결책

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();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top