【问题标题】:Unity - How to resolve an inherited base constructor?Unity - 如何解决继承的基本构造函数?
【发布时间】:2019-11-20 12:51:46
【问题描述】:

使用 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 中处理这些基本构造函数?

【问题讨论】:

  • “具体类型无法在运行时解析”到底是什么意思?您的MyValidationResult 不是被容器解析还是发生了什么? MyValidationResult 将在创建时调用基类的构造函数。
  • 意图从哪里获取消息和标签?恕我直言,我不认为您使用的是正确的 DI。 IoC 容器应仅放置在应用程序的根目录中。如果您的依赖项(例如您的情况)是灵活的并且可以更改,则 DI 不好。 DI 用于依赖项,这看起来更像是数据,我永远不会将其放入 IoC 容器中。

标签: c# .net wpf mvvm unity-container


【解决方案1】:

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

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

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

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

或者

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

不管怎样。

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

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

【讨论】:

  • 您解析对象而不是构造函数。 - 是的,我意识到这一点......
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多