我需要在基于 Prism 的容器内托管多个模块(全部使用 Caliburn Micro 完成)。在容器内,可以创建来自同一模块的多个 View (示例:可以从计算器模块创建科学和金融计算器)。
我使用 Unity 进行 DI,因此在所有模块中覆盖了 Caliburn Micro 的 Bootstrap ,以便从 Unity 容器进行解析。
如CM's IoC class 是静态类,注册其依赖项的最后一个模块会覆盖 ( previous one ) - 请参阅 IoC.GetInstance = GetInstance 行。
我非常喜欢 Sniffer 建议的想法,但每个模块都会创建自己的子容器,因此它不适用于我的场景。
最佳答案
我会提出一个我认为可行的解决方案。默认情况下,CM 分配 IoC.GetInstance()
和所有其他Func<>
代表们 BootstrapperBase
就像这样:
IoC.GetInstance = this.GetInstance
哪里this.GetInstance
只是 BootstrapperBase
中的一个方法它是虚拟的、空的,因此您可以在自己的派生 Bootstrap 中覆盖它。
我尝试的解决方案:存储对已注册内容的引用 IoC.GetInstance
并在新的 GetInstance
中调用它覆盖,并对其他两个静态 Func<>
执行此操作的 IoC
.
在构造函数中或 Configure()
Bootstrap 的方法,为那些静态 Func<>
提供钩子(Hook)代表IoC
相互包裹,像这样:
public class CalculatorBootstrapper : BootstrapperBase {
private Func<Type, string, object> _previousGet;
public override void Configure() {
_previousGet = IoC.GetInstance; // store reference to whatever was stored previously
IoC.GetInstance = this.GetInstance;
}
public override Object GetInstance(Type type, string key) {
var result = null;
if (_previousGet != null)
result = _previousGet(type, key);
if (result == null) {
// Try to use the local container here
}
return result;
}
}
关于c# - 处理 Caliburn Micro 的静态 IoC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743899/