首页 > 解决方案 > Unity - 如何解决继承的基本构造函数?

问题描述

使用 Unity & Prism,尝试在运行时解析接口。

登记

this.unityContainer.RegisterType<IMyValidationResult, MyValidationResult>(new ContainerControlledLifetimeManager());

具体实施

public class MyValidationResult : ValidationResult , IMyValidationResult
{       
    public MyValidationResult(string message, string tag)
        : base(message, null, "", tag, null)
    { }

    public MyValidationResult(string message, string tag = "", string key = "")
        : base(message, null, key, tag, null)
    { }

    // Etc.

然后我IMyValidationResult通过构造函数注入将其注入视图模型。继承ValidationResult的是Microsoft.Practices.EnterpriseLibrary.Validation类。显然,具体类型无法在运行时解析。有没有办法在 Unity 中处理这些基本构造函数RegisterType

标签: c#.netwpfmvvmunity-container

解决方案


你的问题的字面答案是:你不能。

您解析对象而不是构造函数。

您应该在继承的 ctor 的 ctor 中添加您需要的任何参数,基类永远不会被解析,因为它没有单独实例化。你正在解决的叶子类是被实例化的东西。

这意味着无论键是什么,您都需要将其作为参数添加到 MyValidationResult 的 ctor 并将其提供给 Unity。

或者

在 MyValidationResult ctor 中添加一些代码以获取或实例化密钥并将其提供给基本 ctor。

无论哪种方式。

确保具有最多参数的 ctor 是您所依赖的那个。

当您使用 DI 时,拥有多个 ctor 通常是个坏主意,因为它很容易让您混淆将使用哪个。


推荐阅读