asp.net-mvc - EF 上下文管理

标签 asp.net-mvc entity-framework

使用 MVC 应用程序时管理 Entity Framework 上下文的最佳方法是什么?

我正在使用存储库/服务模式。

编辑

浏览完其中一些问题后:stackoverflow.com/users/587920/sam-striano,我比以前更困惑了。有人说每个存储库使用上下文,但是如果我想在一个 Controller 方法中使用多个存储库怎么办?

为了遵循良好的分离设计,如何在 MVC 应用程序中使用 UnitOfWork 而不使其依赖于 EF?我希望能够使用模拟上下文对我的 Controller 、模型、服务等进行单元测试?

最佳答案

使用依赖注入(inject)器/控制反转框架,例如:

  1. 忍者
  2. Autofac
  3. 结构图
  4. 团结

使用 IoC 容器,您可以告诉它如何管理单个数据上下文(最常见的是每个请求)。当您将数据上下文设置为每个请求时,容器将自动神奇地为任何需要数据上下文的类提供每个请求相同的数据上下文。

这是一个good article关于设置 Ninject。

假设您使用的是通用存储库,您的代码最终很可能会是什么样子:

Ninject 模块:

public class NinjectRegistrationModule : NinjectModule
{
    public override void Load()
    {
        Bind<MyDataContext>().ToSelf().InRequestScope();
        Bind(typeof(RepositoryImplementation<>)).ToSelf().InRequestScope();

    }
}

通用存储库:

public RepositoryImplementation<T> : IRepository<T> where T : class
{
    MyDataContext _dataContext;

    public RepositoryImplementation<T>(MyDataContext dataContext)
    {
        _dataContext = dataContext;
    }

    // bunch of methods that utilize _dataContext
}

服务等级:

public class MyServiceClass
{
    IRepository<SomeEntity> _someEntityRepository;

    public MyServiceClass(IRepository<SomeEntity> someEntityRepository)
    {
        _someEntityRepository = someEntityRepository;
    }

    // do stuff with _someEntityRepository = someEntityRepository;
}

Controller :

public class MyController
{
    MyServiceClass _myServiceClass;

    public MyController(MyServiceClass myServiceClass)
    {
        // Ninject will auto-magically give us a myServiceClass
        // which will Ninject will inject a repository into MyServiceClass's constructor
        _myServiceClass = myServiceClass;
    }

    public ActionResult MyAction()
    {
        // use _myServiceClass to do stuff
        return View();
    }
}

关于asp.net-mvc - EF 上下文管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205606/

相关文章:

c# - Entity Framework 播种导致插入语句与外键冲突

c# - Entity Framework ICollection 创建内表

javascript - 错误页面总是在部分 View 中加载

.net - “IConfigurationSection”不包含 'Get' 的定义并且没有可访问的扩展名

javascript - 更改 TextBoxFor 只读属性以决定是否选中复选框

c# - 构建 : error MSB4062 Microsoft. Build.Tasks.ResolveComReference 时出现 .NET Core 错误

c# - 如何更改 Entity Framework Code First 中的默认命名约定?

c# - 迭代 T4 脚手架中的 [ComplexType] 属性?

asp.net-mvc - 如何为 ASP.NET MVC 站点的 OpenId 用户分配角色?

c# - Entity Framework 不会在 SQL Express (MDF) 中保留数据