每在ASP.NET MVC请求一个的DbContext(无IOC容器) [英] One DbContext per request in ASP.NET MVC (without IOC container)

查看:242
本文介绍了每在ASP.NET MVC请求一个的DbContext(无IOC容器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果这已经回答了,但你如何保证每个请求一个实体框架的DbContext,如果你不使用IoC容器? (我已经遇到到目前为止,这些问题的答案涉及IOC容器的解决方案。)

Apologies if this has already been answered, but how do you guarantee one Entity Framework DbContext per request if you are not using an IOC container? (The answers I've come across so far deal with IOC container solutions.)

这似乎是大多数解决方案钩到 HttpContext.Current.Items 词典,但你如何保证处置的DbContext的请求时完成? (或者是处理与EF 的DbContext ?不是绝对必要)

It seems like most solutions hook into the HttpContext.Current.Items dictionary, but how do you guarantee disposal of the DbContext when the request is finished? (Or is disposal not absolutely necessary with an EF DbContext?)

修改

我目前实例化和处置我的DbContext在我的控制器,但我也有我的ActionFilters的DbContext和我的MembershipProvider的几个单独的实例(我只注意到,还有一对夫妇验证)。所以,我想这可能是集中我的DbContext实例化和存储以减少开销是个好主意。

I'm currently instantiating and disposing my DbContext in my controllers, but I also have several separate instantiations of my DbContext in ActionFilters and my MembershipProvider (and I just noticed, also a couple validators). So, I thought it might be a good idea to centralize instantiation and storage of my DbContext to reduce overhead.

推荐答案

我会使用的BeginRequest / EndRequest方法,这有助于确保您的上下文是妥善处置当请求结束与

I would use the BeginRequest/EndRequest method, this helps ensure that your context is disposed of properly when the request is over with.

protected virtual void Application_BeginRequest()
{
    HttpContext.Current.Items["_EntityContext"] = new EntityContext();
}

protected virtual void Application_EndRequest()
{
    var entityContext = HttpContext.Current.Items["_EntityContext"] as EntityContext;
    if (entityContext != null)
        entityContext.Dispose();
}

而在你的EntityContext类...

And in your EntityContext class...

public class EntityContext
{
    public static EntityContext Current
    {
        get { return HttpContext.Current.Items["_EntityContext"] as EntityContext; }
    }
}

这篇关于每在ASP.NET MVC请求一个的DbContext(无IOC容器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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