c# - 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
?
解决方案
你的问题的字面答案是:你不能。
您解析对象而不是构造函数。
您应该在继承的 ctor 的 ctor 中添加您需要的任何参数,基类永远不会被解析,因为它没有单独实例化。你正在解决的叶子类是被实例化的东西。
这意味着无论键是什么,您都需要将其作为参数添加到 MyValidationResult 的 ctor 并将其提供给 Unity。
或者
在 MyValidationResult ctor 中添加一些代码以获取或实例化密钥并将其提供给基本 ctor。
无论哪种方式。
确保具有最多参数的 ctor 是您所依赖的那个。
当您使用 DI 时,拥有多个 ctor 通常是个坏主意,因为它很容易让您混淆将使用哪个。
推荐阅读
- c - 如何找到两组的笛卡尔积
- php - 当我单击一个按钮时,它没有通过 ajax jquery 将数据发送到 changePassword.php
- linux - 列出可用于软件包的先前版本并通过 apt-get 安装其中一个
- c++ - 范围解析运算符无法与模板一致地工作
- swift - MacOS 应用程序可以在 Bundle.main 中创建新文件吗?
- ios - 用于 MIDI 播放和录音的 AVAudioEngine 同步
- moodle - 将数据传递给moodle服务时检测到无效的参数值
- vue.js - Vue嵌套v-for,获取父级索引
- node.js - 如何从以太坊区块链中检索数据
- php - 尝试使用Angular通过POST发送数据到cURL