Unity-如何解析继承的基本构造函数?

问题描述 投票:0回答:1

使用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注入视图模型。继承的ValidationResultMicrosoft.Practices.EnterpriseLibrary.Validation类。显然,具体类型无法在运行时解析。有没有一种方法可以在Unity RegisterType中处理这些基本构造函数?

c# .net wpf mvvm unity-container
1个回答
0
投票

您的问题的字面回答是:您不能。

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

您应该在继承的ctor的ctor的基础上添加所需的任何参数,因为不会单独实例化基类,所以永远不会解析基类。您要解析的叶子类是实例化的东西。

意味着任何键,您都需要将其作为参数添加到MyValidationResult的ctor中,并将其提供给Unity。

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

无论哪种方式。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.