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

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

问题描述

抱歉,如果已经回答了这个问题,但是如果您没有使用 IOC 容器,您如何保证每个请求有一个实体框架 DbContext?(到目前为止,我遇到的答案都是关于 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 和我的 MembershipProvider 中也有几个单独的 DbContext 实例(我刚刚注意到,还有几个验证器).所以,我认为集中我的 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天全站免登陆