【问题标题】:MVC 3: Injecting multiple repositories into a single controllerMVC 3:将多个存储库注入单个控制器
【发布时间】:2012-10-20 09:59:54
【问题描述】:

我的表示层在 MVC 3 中。

我有一个返回存储库的数据访问层。每个存储库都映射到一个表。

例如,我有以下存储库接口:

  • ICustomerRepository
  • ICustomerTypeRepository

我有这些存储库的实体框架实现。这些实现在运行时使用 Ninject 注入。

我有两个控制器:

  • 客户控制器
  • 客户类型控制器

每个控制器都有一组 CRUD 例程。客户必须有一个类型。

为了创建客户记录,我需要使用 EFCustomerTypeRepository。

我现在在 CustomerController 中有一个构造函数,看起来像这样:

public class CustomerController: Controller
{
   private ICustomerRepository customerRepository;        
   private ICustomerTypeRepository customerTypeRepository; 

   public CustomerController(ICustomerRepository customerRepository, 
                             ICustomerTypeRepository customerTypeRepository)
   {
      this.customerRepository = customerRepository;            
      this.customerTypeRepository = customerTypeRepository;
   }     

...

开发处于早期阶段,如果我采用这种方法,那么在接下来的几天内,这个构造函数将有 5 个或更多参数。这看起来不对。

我可以将所有这些逻辑存储在 EFCustomerRepository 中,但是,这将打破单一责任原则。所以我不会那样做。

最后,我可以包装这些存储库并将单个 RepositoryWrapper 类型的对象传递给我的控制器。

我不想介绍更多的框架和工具。我的目标是实现松散耦合和易于扩展,但目前我在将更多参数传递给构造函数或为存储库编写包装器之间陷入困境。

我正在使用 MVC 3、EF 4.1、Ninject、Moq 和 Automapper。谢谢

【问题讨论】:

标签: asp.net-mvc-3 architecture controller repository inversion-of-control


【解决方案1】:

我想说您必须注意代码中的聚合(从领域驱动设计的角度来看)。因此,如果您可以让一个类封装许多其他小类,而这些小类没有用自己存储它们,您就可以创建一个很好的对象图,并且只有一个 ICustomerRepository 封装了对例如客户类型的内部引用。

【讨论】:

  • 最终编写了一个聚合来将我的存储库包装到一个服务中。
【解决方案2】:

无论如何,将多个存储库注入到控制器构造函数中并不一定是坏习惯。它被称为“构造函数过度注入”,请参阅 Mark Seemann 关于此主题的书。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多