【发布时间】:2019-04-13 04:04:24
【问题描述】:
我有 Prism 7.1、Unity DI 5.8.11 和 .NET 框架 4.7 的 WPF 项目
我有 BaseViewModel,所有的 ViewModel 类都将从那里继承
public abstract class BaseViewModel : BindableBase
{
[Dependency]
protected IEventAggregator EventAggregator { get; set; }
// just default constructor, no other constructor is needed
}
这里是 ViewModel 类之一的示例
public class TablesViewModel : BaseViewModel
{
public TablesViewModel()
{
EventAggregator.GetEvent<OperatorChangedEvent>().Subscribe(.....);
}
}
和寄存器的类型如下
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterInstance<IEventAggregator>(new EventAggregator());
}
现在,发生的情况如下:首先调用 BaseViewModel 的构造函数,然后调用 TablesViewModel 的构造函数,然后由 Unity DI 设置 Dependency 属性,这是事件的逻辑顺序,但它不适合我。
TablesViewModel 的构造函数给出了一个空引用异常,因为 EventAggregator 属性仍然为空。
我不想使用构造函数依赖注入,这将迫使我为所有 ViewModel 类创建很多非默认构造函数。
同时,我需要在构造函数处订阅EventAggregator(因为没有其他好的地方可以这样做,如果有请告诉我)。
我该如何解决这个问题
【问题讨论】:
标签: wpf dependency-injection unity-container prism eventaggregator