使用Caliburn Micro将EventAggregator注入ViewModel

Dea*_*uga 1 c# mvvm caliburn.micro

从EventAggregator上的Caliburn Micro文档中提取:

// Creating the EventAggregator as a singleton.
public class Bootstrapper : BootstrapperBase {
    private readonly SimpleContainer _container =
        new SimpleContainer();

     // ... Other Bootstrapper Config

    protected override void Configure(){
        _container.Singleton<IEventAggregator, EventAggregator>();
    }

    // ... Other Bootstrapper Config
}

// Acquiring the EventAggregator in a viewModel.
public class FooViewModel {
    private readonly IEventAggregator _eventAggregator;

    public FooViewModel(IEventAggregator eventAggregator) {
        _eventAggregator = eventAggregator;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以问题是如何让Bootstrapper创建的EA实例注入你的虚拟机?

var svm = new SomeViewModel(?);

我尝试使用Caliburn.Micro.IoC.Get方法,但这不起作用......

Ibr*_*jar 7

不,您不会var svm = new SomeViewModel(?)也不会使用IoC.Get,因为服务位置正在成为一种反模式.
文章作者提出的模式是最佳实践,即您应该通过构造函数注入将依赖项注入需要它们的对象.
我不知道如何以任何其他方式说出来,但让您的应用程序可以组合并为您创建一个架构表示层.
我会查看Screens,Conductors和Composition文章,因为它有一些与我说的相关的好点子,并且它附带的应用程序很棒.
我还会读到有关依赖注入的内容.

  • @DeanKuga这就是我的观点,你不是手动创建一个视图模型,你让CaliburnMicro从引导程序中为你创建整个对象图,如果你有一个ViewModel,你通过构造函数接收到eventAggregator,请保持对它的引用如果ViewModel需要手动创建在构造函数中使用IEventAggregator的其他ViewModel,则只读实例变量并在ViewModel中使用此实例. (2认同)