如何访问没有明确提及开放的DbContext? [英] How to access open DbContext without explicit reference?

查看:106
本文介绍了如何访问没有明确提及开放的DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直有一点点实体框架,现在,我已经遇到几种方案,其中两个上下文将试图访问同一实体等,所以我想,如果可能,我不开放/关闭以最好的方式我dbcontexts。

I've been working with the entity framework for a little bit now, and I've come across several scenarios where two contexts would try to access the same entity etc, so I'm wondering if perhaps I'm not opening/closing my dbcontexts in the best way.

目前我基本上是在我的每个控制器的基本MVC应用程序成立了原始的方法,这意味着我必须在控制器上的私人的DbContext领域打开的DbContext,我重写控制器的Dispose方法调用dispose上下文

Currently I basically open a DbContext on each of my controllers the way the basic MVC app was set up originally, which means I have a private dbcontext field on the controller, and I override the controller's dispose method to call dispose on the context.

不过,我有时也使对数据库的查询中我的一些其他类,可以从控制器,它也有一个开放的环境中被调用的。

However I also sometimes make queries against the db in some of my other classes, which can get called from within the controller, which also has a context open.

有没有明确的处理程序来访问一个开放的环境的一种方式?它不会真正意义对我来说,绕过通过十几种不同的方法的DbContext参考。

Is there a way to access an open context without an explicit handler? It wouldn't really make sense for me to pass around a DbContext reference through a dozen different methods.

推荐答案

使用依赖注入

正如其他人所说,并可能会重申,正确的道路通常被认为是依赖注入。

As others have said and will probably reiterate, the 'right way' is often considered to be dependency injection.

在我的最新项目,我组织的事情,使我几乎与项目完成,DI一直如此轻松,我做我自己(而不是使用注射器)。在一个主要因素一直秉承严格公正这个结构:

In my latest project, I've organized things so that I'm almost done with the project and DI has been so effortless that I'm doing it myself (rather than using an injector). One major factor in that has been adhering fairly strictly to this structure:

                           WebProject
                             |    |
                             |   DataServices
                             |    |        | 
                           ViewModels    EntityModels

一个工作单元中访问所有的数据服务时,通过一个单一的DataServiceFactory实例,这需要MyDbContext的一个实例。另一个因素是一个完全RESTful应用程序的设计 - 这意味着我不必在我的code点缀持久性功能

Access to all data services during one unit of work occurs through a single DataServiceFactory instance, that requires an instance of MyDbContext. Another factor has been an entirely RESTful application design - it means I don't have to intersperse persistence functionality throughout my code.

不依赖注入

这是说,也许DI为不适合你在这个项目上。也许:

That said, maybe DI isn't right for you on this project. Maybe:


  • 您不打算编写单元测试

  • 您需要更多的时间来了解DI

  • 您的项目结构已经有了EF深深融入

在ASP.NET MVC,工作单位往往完全与请求生命周期相吻合。这样一来,就可以懒洋洋地实例化,而不是使用DI每个请求的资源库'单身'。下面是当前上下文作为后备存储,举行经典的单例模式的的DbContext

In ASP.NET MVC, the unit of work often entirely coincides with the request lifetime - i.e. HttpContext.Current. As a result, you can lazily instanciate a repository 'singleton' per-request, instead of using DI. Here is a classic singleton pattern with current context as the backing store, to hold your DbContext:

public class RepositoryProxy {
    private static HttpContext Ctx { get { return HttpContext.Current; } }
    private static Guid repoGuid = typeof(MyDbContext).GUID;

    public static MyDbContext Context {
        get {
            MyDbContext repo = Ctx.Items[repoGuid];
            if (repo == null) {
                repo = new MyDbContext();
                Ctx.Items[repoGuid] = result;
            }
            return repo;
        }
    }

    public static void SaveIfContext() {
        MyDbContext repo = Ctx.Items[repoGuid];
        if (repo != null) repo.SaveChanges();
    }
}

您可以的SaveChanges 自动过,如果你感觉特别懒惰(你仍然需要手动调用它来检查的副作用,当然,像检索ID为新项目):

You can SaveChanges automatically too, if you are feeling especially lazy (you'll still need to call it manually to inspect side-effects, of course, like retrieving the id for a new item):

public abstract class ExtendedController : Controller {
    protected MyDbContext Context {
        get { return RepositoryProxy.Context; }
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext) {
        RepositoryProxy.SaveIfContext();
        base.OnActionExecuted(filterContext);
    }
}

这篇关于如何访问没有明确提及开放的DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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