ASP.NET 中每个请求的实体框架对象上下文? [英] Entity Framework Object Context per request in ASP.NET?

查看:24
本文介绍了ASP.NET 中每个请求的实体框架对象上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为每个请求使用单个 ObjectContext 是否被认为是一种好习惯?我读到这些对象应该是短暂的,并且实例化成本不是很高,但这是否使每个请求对其中一个具有吸引力?如果是,是否有任何模式可以正确实现这一点?

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?

推荐答案

是的,让 ObjectContext/DbContext 具有每个 HttpRequest 的生命周期是一种公认​​的方法.这是一个示例我在另一个答案中提供了.

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

然而,最好将这些生命周期管理留给 IoC 库.著名的有温莎城堡Autofac.

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

更新:
要处理您的上下文,您可以使用 Global.asax 中的 Application_EndRequest 方法.以下代码未经测试,但您会明白:

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

这篇关于ASP.NET 中每个请求的实体框架对象上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆