每个模块的 Prism 统一容器

Prism unity container per module

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

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

    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 以使用另一个容器作为模块?

在每个模块初始化时,没有直接传递新容器(child/no 子容器)的方法。我遇到过类似的情况,我需要模块在特定的统一容器(子容器)中注册它们的类型。我就是这样做的。
首先,我新建了一个继承自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 实现,它使用父 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);
    }
}