【问题标题】:Use Unity Property Dependency Injection with EventAggregator将 Unity 属性依赖注入与 EventAggregator 一起使用
【发布时间】: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


    【解决方案1】:

    属性不能在类的实例创建之前设置,即EventAggregator属性在构造函数执行之前永远不会设置。

    如果您需要在构造函数中访问事件聚合器,您应该使用构造函数依赖注入或从某个静态属性中检索事件聚合器。

    【讨论】:

    • 关于静态属性的好建议,因为我不会接受构造函数依赖注入的想法,但这不会消除 DI 模式的好处吗?
    • 你对在构造函数之外的其他地方订阅事件有什么想法吗?
    • ServiceLocator.Current 是一个静态属性,是的,这确实消除了 DI 模式的好处。 “不考虑构造函数依赖注入”选项也是如此。
    【解决方案2】:

    我不想使用构造函数依赖注入,这将迫使我为所有 ViewModel 类创建很多非默认构造函数。

    您想要具有依赖关系的类的非默认构造函数。这就是依赖注入的全部意义:类型通过它们的构造函数参数告诉用户他必须给它们操作什么。

    有很多方法可以使用非默认构造函数创建视图模型,例如Prism 的ViewModelLocator 或 Unity 的自动工厂。除非绝对必要,否则您不想诉诸使用 ServiceLocator,但从技术上讲,一个邪恶的人可以做这样的事情:

    public abstract class BaseViewModel : BindableBase
    {
        protected IEventAggregator EventAggregator { get; } = ServiceLocator.Current.GetInstance<IEventAggregator>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-03
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多