处理Caliburn Micro的静态IoC

时间:2013-09-11 14:26:10

标签: c# .net wpf prism caliburn.micro

我需要在基于Prism的容器内托管多个模块(全部使用Caliburn Micro完成)。在容器内,可以创建来自同一模块的多个视图(例如:可以从计算器模块创建科学和金融计算器)。

我正在使用Unity for DI,因此在所有模块中都覆盖了Caliburn Micro的引导程序,以便从统一容器中解析。

由于CM's IoC类是一个静态类,注册它的依赖项的最后一个模块会覆盖(previous one) - 请参阅IoC.GetInstance = GetInstance行。

我非常喜欢Sniffer建议的想法,但每个模块都会创建自己的子容器,因此它不适用于我的场景。

1 个答案:

答案 0 :(得分:4)

我会建议一个我认为可行的解决方案。默认情况下,CM会在IoC.GetInstance()中分配Func<>和所有其他BootstrapperBase代表,就像这样:

IoC.GetInstance = this.GetInstance

this.GetInstance只是BootstrapperBase中虚拟且空的方法,因此您可以在自己的派生引导程序中覆盖它。

我尝试过的解决方案:存储对已在IoC.GetInstance注册的内容的引用,并在新的GetInstance覆盖中调用它,并针对其他两个静态Func<>执行此操作IoC

在bootstrappers的构造函数或Configure()方法中,为Func<>中相互包装的静态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;
    }
}
相关问题