2015-09-23 23 views
3

我一直在阅读有关构造函数过度注入的问题。 这一切都是有道理的,这是一个标志,SRP没有被正确地遵循等等(我正在使用Ninject!)如何在MVVM应用程序中处理构造函数过度注入

但是,我很难理解如何解决这个问题在我的案件。 最大的问题是在我的视图模型中,我注入了DTO映射器和存储库以与我的属性一起使用。

这里是什么我的视图模型构造可能看起来像一个例子:

public MainViewModel(
     IGenericRepository<MainDbContext, Product> productRepository, 
     IGenericRepository<MainDbContext, Person> personRepository, 
     IGenericRepository<MainDbContext, Order> orderRepository, 
     ProductMapper productMapper, 
     PersonMapper personMapper, 
     OrderMapper orderMapper, 
     IViewModelLoader viewModelLoader, 
     IEventAggregator eventAggregator) 
    { 
     _productRepository = productRepository; 
     _personRepository = personRepository; 
     _orderRepository = orderRepository; 
     _productMapper = productMapper; 
     _personMapper = personMapper; 
     _orderMapper = orderMapper; 
     _viewModelLoader = viewModelLoader; 
     _eventAggregator = eventAggregator; 

     _eventAggregator.Subscribe(this); 

    } 

我的猜测是,我无法正常使用库/映射器,他们应该被移出视图模型的......我我不确定究竟在哪里或如何。 这是我的问题的原因。

应用程序的体系结构是这样的:

Company.Product.Core 
Company.Product.DataAccess 
Company.Product.Domain 
Company.Product.Presentation 

的GenericRepository放在里面Company.Product.DataAccess.Repositories 和映射器内Company.Product.Domain.Mappers

+0

您是否从一个窗口/视图访问产品,人员和订单? –

+0

@YacoubMassad。上面的存储库已被重命名为一些示例。但我真正的构造函数看起来像这样,是的,他们都在一个视图中访问。^ –

+0

为什么你注入你的构造函数?你在使用某种IoC容器吗? – Lance

回答

3

综观构造器的表,它看起来像成双:

  • productRepository/productMapper
  • personRepository/personMapper
  • orderRepository/orderMapper

这似乎表明,MainViewModel组成相关产品,人员和订单东西。

你可以改为建模它,而不是组成另外三个视图模型?假设ProductViewModel,PersonViewModel,OrderViewModel类。

它甚至必须是这三个类吗? MainViewModel是否可以组成任意数量的其他查看模型?

这将构造减少这样的事情:

public MainViewModel(
    IReadOnlyCollection<IViewModel> viewModels, 
    IViewModelLoader viewModelLoader, 
    IEventAggregator eventAggregator) 

这似乎更合理。

这实质上是Composite pattern的实现,它通常非常适合UI建模 - 它通常被称为复合用户界面


另一件事,让我奇怪的是IVewModelLoader做什么?

+0

梦幻般的答案马克!关于存储库和映射器成对出现,你是对的。几乎每个我添加的资源库都会出现这种情况,除了某些数据不需要映射的例外。 我很高兴你回答,因为我实际上正在阅读有关fascade服务的文章以及上面链接的相关答案。我会尝试实施你在这里建议的内容,并让你知道它是怎么回事!关于IViewModelLoader ..这就是开启我的观点和验证(TODO atm哈哈)的原因。该课程如下所示:http://pastebin.com/hbCEc41s –