如何处理MVVM应用程序中的构造函数过度注入

本文关键字:构造函数 注入 应用程序 MVVM 何处理 处理 | 更新日期: 2023-09-27 18:14:27

我一直在阅读关于构造函数过度注入的问题。这一切都是有道理的,这是SRP没有被正确遵循的迹象(顺便说一下,我正在使用Ninject !)

然而,我很难理解如何在我的情况下解决这个问题。最大的问题是在我的视图模型中,我正在注入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

如何处理MVVM应用程序中的构造函数过度注入

查看构造函数列表,它看起来像是成对出现的:

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

这似乎表明MainViewModel构成了与产品、人员和订单有关的东西。

你能代替它建模,使它而不是组成其他三个视图模型吗?假设ProductViewModel, PersonViewModel, OrderViewModel类…?

必须是这三个类吗?MainViewModel可以代替组成任何数量的其他视图模型?

将构造函数简化为如下所示:

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

似乎更合理。

这将本质上是复合模式的一个实现,它通常很适合UI建模——它通常被称为复合UI


另一件让我好奇的事情是IVewModelLoader做什么?