2017-04-20 91 views
1

我在我的應用程序中有兩個模塊,並且想要在另一個容器中註冊第二個模塊的類型。沒有找到任何方法來做到這一點。棱鏡統一容器每個模塊

只有這樣,我現在看到的是添加前綴可重複使用的類型那樣:

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"))); 

有什麼辦法來配置棱鏡使用另一個容器模塊?

+1

爲什麼你需要一個單獨的容器?如果你這樣做,你可以創建一個? – mm8

+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它使用提供了在父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); 
    } 
} 
+0

比我的解決方案好得多。我解決了問題,但與幾個黑客。謝謝! –