如何将依赖项注入MVVM View Model类?

ric*_*cky 5 c# wpf dependency-injection mvvm autofac

我熟悉WPF和MVVM模式。现在,我正在尝试使用Autofac在我的新WPF应用中练习依赖注入模式。我想弄清楚如何将依赖项注入MVVM View Model类。

如下面的代码所示,我有一个根视图模型类MainViewModel,它可以MonitorPageViewModel在需要时创建其他视图模型(例如)实例。在中MonitorPageViewModel,还需要在需要时创建其他子视图模型(例如MonitorDashboardViewModel)实例。而所有这些视图模型可能有几个依赖(ILoggerIRepository<RawMessage>IParsingService,等)。

在我以前的WPF项目中,没有使用任何IoC容器,我总是new在需要时在父视图模型中使用子视图模型,并使用ServiceLocator提供所需的服务。现在,我想找出一种更多的依赖注入方式来执行此操作。

我有几种方法(在下面的代码中演示),但是我对其中任何一种都不满意。

  1. 使用IoC容器获取响应来创建MainViewModel;并将IoC容器实例注入到MainViewModel; 然后,使用IoC容器实例解析子视图模型构造函数所需的每个对象。如果子视图模型类需要解析其他类,则将IoC注入其中。[ 听起来另一个ServiceLocator ]。
  2. 注入MainViewModel视图模型及其后代视图模型所需的所有服务,并沿视图模型链传递服务。以及需要new的视图模型实例。[ 需要注入大量服务,并将其传递给 ]

我不想Caliburn.Micro在该项目中使用MVVM框架。有没有简单而优雅的解决方案?

public interface ILogger
{
    // ...
}

public interface IRepository<T>
{
    // ...
}

public interface IStatisticsService
{
    // ...
}

public class RawMessage
{
    // ...
}

public class Device
{
    // ...
}

public class Parser
{
    // ...
}


public interface IParsingService
{
    void Parse(Parser parser);
}

public class DockPaneViewModel : ViewModelBase
{
    // ...
}

public class HomePageViewModel : DockPaneViewModel
{
    public HomePageViewModel(ILogger logger)
    {
        // ...
    }
}

public class MonitorDashboardViewModel : DockPaneViewModel
{
    public MonitorDashboardViewModel(IStatisticsService statisticsService)
    {
        // ...
    }
}

public class MonitorPageViewModel : DockPaneViewModel
{
    public MonitorPageViewModel(ILogger logger, IRepository<RawMessage> repository,
        IRepository<Parser> parserRepository, IParsingService parsingService)
    {
        // ...
    }

    public void CreateDashboard()
    {
        IStatisticsService statisticsService = ??; // how to resolve the service?
        var dashBoardVm = new MonitorDashboardViewModel(statisticsService); // how to create this? 
    }
}

public class ResourceManagementViewModel : DockPaneViewModel
{
    public ResourceManagementViewModel(ILogger logger, IRepository<Device> deviceRepository)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这是MainViewModel带有替代构造函数的

public class MainViewModel : ViewModelBase
{
    public ObservableCollection<DockPaneViewModel> DockPanes
    {
        get;
        set;
    } = new ObservableCollection<DockPaneViewModel>();

    #region approach 1
    // use the IOC container take the response to create MainViewModel;
    // and inject the Ioc Container instance to MainViewModel;
    // then, use the IOC container instance to resovle every thing the child view models need
    private readonly ISomeIocContainer _ioc;
    public MainViewModel(ISomeIocContainer ioc)
    {
        _ioc = ioc;
    }

    public void ResetPanes_1()
    {
        DockPanes.Clear();
        DockPanes.Add(new HomePageViewModel(_ioc.Resolve<ILogger>())); // how to new child view model and how to provide the constructor parameters?
        DockPanes.Add(new MonitorPageViewModel(_ioc.Resolve<ILogger>(),
            _ioc.Resolve< IRepository<RawMessage>>(), 
            _ioc.Resolve<IRepository<Parser>>(),
            _ioc.Resolve<IParsingService>())); // also need to inject ISomeIocContainer to MonitorDashboardViewModel for resolve IStatisticsService
        DockPanes.Add(new ResourceManagementViewModel(_ioc.Resolve<ILogger>(), 
            _ioc.Resolve<IRepository<Device>>()));
        // add other panes
    }
    #endregion

    #region approach 2
    // pasing all dependencies of MainViewModel and all descendant View Models in to MainViewModel,
    // and pass dependencies along the ViewModel chain.
    private readonly ILogger _logger;
    private readonly IRepository<RawMessage> _repository;
    private readonly IRepository<Parser> _parserRepository;
    private readonly IRepository<Device> _deviceRepository;
    private readonly IParsingService _parsingService;
    private readonly IStatisticsService _statisticsService;
    public MainViewModel(ILogger logger, IRepository<RawMessage> repository,
        IRepository<Parser> parserRepository, IRepository<Device> deviceRepository,
        IParsingService parsingService, IStatisticsService statisticsService)
    {
        _logger = logger;
        _repository = repository;
        _parserRepository = parserRepository;
         _deviceRepository = deviceRepository;
        _parsingService = parsingService;
        _statisticsService = statisticsService;
    }

    public void ResetPanes_2()
    {
        DockPanes.Clear();
        DockPanes.Add(new HomePageViewModel(_logger)); // how to new child view model and how to provide the constructor parameters?
        DockPanes.Add(new MonitorPageViewModel(_logger, _repository, _parserRepository, _parsingService)); // also need pass statisticsService down 
        DockPanes.Add(new ResourceManagementViewModel(_logger, _deviceRepository));
        // add other panes
    }
    #endregion
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

有时候回到基础并保持简单(KISS)往往会奏效。

在这种情况下想到的是显式依赖原则纯依赖注入

MainViewModel由要么做太多的明显注入容器(大不)还是有办法许多依赖(代码异味)。尝试缩小类应该在做什么(SRP)

可以这么说,主视图模型需要窗格的集合。那为什么不给它它所需要的。

public class MainViewModel : ViewModelBase {
    public ObservableCollection<DockPaneViewModel> DockPanes { get; set; }

    //Give the view model only what it needs
    public MainViewModel(IEnumerable<DockPaneViewModel> panes) {
        DockPanes = new ObservableCollection<DockPaneViewModel>(panes);
    }

    public void ResetPanes() {
        foreach (var pane in DockPanes) {
            pane.Reset();
        }
        //notify view
    }
}
Run Code Online (Sandbox Code Playgroud)

注意底板的细微变化

public abstract class DockPaneViewModel : ViewModelBase {
    // ...

    public virtual void Reset() {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

主视图模型不应与依赖关系的创建方式有关。它只关心它得到它明确要求的内容。

这同样适用于不同的窗格实现。

如果视图模型需要能够创建多个子代,则将该职责委托给工厂。

public class MonitorPageViewModel : DockPaneViewModel {
    public MonitorPageViewModel(ILogger logger, IRepository<RawMessage> repository,
        IRepository<Parser> parserRepository, IParsingService parsingService, 
        IPaneFactory factory) {
        // ...
    }

    public void CreateDashboard() {
        var dashBoardVm = factory.Create<MonitorDashboardViewModel>();

        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

同样,受试者应承担尽可能少的责任。

View First或ViewModel First被认为是实现问题,如果遵循配置模型上的约定,则实际上并不重要。

如果设计做得好,那么使用框架还是纯代码都没关系。

但是,在将所有内容组合在一起时,这些框架确实派上了用场。最简单,最优雅的解决方案是让对象创建对象图,但如果没有该对象,则只能在合成根目录中自行构建。