使用通用存储库模式管理连接 [英] Managing connections with Generic Repository pattern

查看:107
本文介绍了使用通用存储库模式管理连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架4.1和mvc3构建站点.我正在使用通用存储库模式:
http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle .我使用ninject将混凝土存储库注入到控制器中. 我的问题是我的每个dbcontext都不相同,而且如果没有代码大喊不同的上下文不能在同一查询中使用"之类的代码,我将无法运行复杂的查询.我尝试使用单一"方法,但是代码大喊尝试输入已处置的对象(空引用异常)". 有人知道我在做什么错吗?

I am building a site using entity framework 4.1 and mvc3. I am using the Generic Repository pattern:
http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle. I use ninject to inject my concretes repositories to the controllers. My problem is that each of my dbcontext different and I cannot run complex queries without the code shouting something like "different contexts cannot be used in the same query". I tried using the "singleton" approach but then code shouted something like "tried to enter a disposed object (null reference exception)". Does anyone have an idea of what I'm doing wrong?

推荐答案

Singleton模式是应避免的反模式.这就导致难以测试具有各种副作用(例如,已处置的DbContext)的代码.

The Singleton pattern is an anti-pattern that should be avoided. It leads to hard to test code with all kinds of side effects (for example, a disposed DbContext).

UnitOfWork管理不同存储库上的操作.它将跟踪所做的所有更改,然后将这些更改以正确的顺序写入数据库. DbContext已经实现了UnitOfWork模式(尽管最好将DbContext隐藏在自定义UnitOfWork接口的后面).

The UnitOfWork manages operations on different repositories. It will keep track of all the changes that are made and then it will write those changes in the right order to your database. The DbContext already implements the UnitOfWork pattern (Altough it's nicer to hide the DbContext behind a custom UnitOfWork interface).

如果您已经在使用依赖注入槽NInject,那么您几乎就是他们了!您应该更改存储库的构造函数以采用DbContext:

If you are already using dependency injection trough NInject you are almost their! You should change the constructors of your Repository to take a DbContext:

public class MyRepository
{
   private _unitOfWork;

   public MyRepository(DbContext unitOfWork)
   {
      _unitOfWork = unitOfWork;
   }

   ....
}

如果您随后通过 InRequestScope模式将DbContext连接到NInject 一切都应该工作.然后,您的DbContext将被所有存储库共享,并且Ninject将在您的请求结束时将其丢弃.

If you then wire the DbContext to NInject with a InRequestScope mode everything should work. Your DbContext will then be shared by all Repositories and Ninject will dispose of it at the end of your request.

这篇关于使用通用存储库模式管理连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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