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

查看:177
本文介绍了每个请求的实体框架对象上下文中的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每Htt的prequest寿命。 这里我在另一个答案提供了一个样本。

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,最好离开这些一辈子管理层到一个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 方法。下面code未经测试,但你会得到的想法:

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天全站免登陆