每个模块的棱镜统一容器

时间:2017-04-20 13:04:15

标签: wpf xaml prism

我的应用程序中有两个模块,并希望在单独的容器中注册第二个模块的类型。没有找到任何方法可以做到这一点。

我现在看到的唯一方法是为可重复使用的类型添加前缀:

    var foo1 = new Foo("FOO 1");
    parentContainer.RegisterInstance<IFoo>("Foo1", foo1);

    var foo2 = new Foo("FOO 2");
    parentContainer.RegisterInstance<IFoo>("Foo2", foo2);

    parentContainer.RegisterType<IService1, Service1>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IFoo>("Foo1")));
    parentContainer.RegisterType<IService2, Service2>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IFoo>("Foo2")));

有没有办法配置prism来为模块使用另一个容器?<​​/ p>

1 个答案:

答案 0 :(得分:1)

在每个模块初始化时,没有直接传递新容器(子/无子)的方法。我有类似的情况,我需要模块在特定的统一容器(子)中注册他们的类型。我就这样做了。
首先,我创建了一个从UnityContainer继承的新Unity容器。根据目录中的模块名称创建子容器的字典。

public class NewContainer : UnityContainer
{
    private readonly IDictionary<string, IUnityContainer> _moduleContainers;

    public NewContainer(ModuleCatalog moduleCatalog)
    {
        _moduleContainers = new Dictionary<string, IUnityContainer>();
        moduleCatalog.Modules.ForEach(info => _moduleContainers.Add(info.ModuleName, CreateChildContainer()));
    }

    public IUnityContainer GetModuleContainer(string moduleName)
    {
        return _moduleContainers.ContainsKey(moduleName) ? _moduleContainers[moduleName] : null;
    }

}

现在我实现的每个模块都必须从ModuleBase实现,ModuleBase使用在父UnityContainer中为该模块提供的子容器。现在在子容器中注册您的类型。

public abstract class ModuleBase : IModule
{
    protected IUnityContainer Container;

    protected ModuleBase(IUnityContainer moduleContainer)
    {
        var container = moduleContainer as NewContainer;
        if (container != null)
            Container = container.GetModuleContainer(GetType().Name);
    }

    public abstract void Initialize();
}

这就是我在引导程序中使用容器的方法 -

public class NewBootStrapper : UnityBootstrapper
{
    private readonly ModuleCatalog _moduleCatalog;
    private DependencyObject _uiShell;

    public NewBootStrapper()
    {
        _moduleCatalog = Prism.Modularity.ModuleCatalog.CreateFromXaml(new Uri("/projectName;component/ModulesCatalog.xaml",
                UriKind.Relative));         
    }

    protected override IUnityContainer CreateContainer()
    {
        return new DocumentBootStrapperContainer(_moduleCatalog);
    }
    protected override IModuleCatalog CreateModuleCatalog()
    {
        return new AggregateModuleCatalog();
    }
    protected override void ConfigureModuleCatalog()
    {
        ((AggregateModuleCatalog)ModuleCatalog).AddCatalog(_moduleCatalog);
    }
}
相关问题