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

拥有回忆 提交于 2019-11-28 02:04:27

问题


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?


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/16543894/entity-framework-object-context-per-request-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!