Managing connections with Generic Repository pattern

耗尽温柔 提交于 2019-12-08 04:37:58

问题


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?


回答1:


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).

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).

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;
   }

   ....
}

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.




回答2:


Not sure if I'm getting your question or not, but your repositories should be able to work within a "Unit of Work" which would have a single dbcontext.

I find the best place to start this unit of work is on the begin request, which you can setup in your global.asax ( and the end request for tear down )



来源:https://stackoverflow.com/questions/10430880/managing-connections-with-generic-repository-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!