2015-09-25 55 views
0

我正在嘗試將我的統一文件合併到由子容器分隔的單個文件中,以便簡化最終系統配置,但我很難弄清楚它。到目前爲止,我已經實現了我自己的WcfServiceFactory,並且已經覆蓋ConfigureContainer來加載我們的Unity,但是我們無法找到加載子容器的方法。這是我到目前爲止:WCF服務中的統一

public class WcfServiceFactory : UnityServiceHostFactory 
{ 
    /// <summary> 
    /// Configures the container. 
    /// </summary> 
    /// <param name="container">The container.</param> 
    protected override void ConfigureContainer(IUnityContainer container) 
    { 
     if (container == null) 
     { 
      throw new ArgumentNullException("container"); 
     } 
     container.LoadConfiguration(); 
     container.AddExtension(new ConfigExtension()); 

     var childContainer = container.CreateChildContainer(); 
     childContainer.LoadConfiguration(ConfigurationManager.AppSettings["ChildUnityContainer"]); 
    } 
} 

請讓我知道,如果你有這樣做的方式。

+0

從我上面看到,您正在使用多個子容器配置來到達一個「完全」配置的容器來解析對象。否則,如何知道使用什麼容器來解析特定的請求。那是對的嗎? –

回答

2

Unity配置是附加的,所以我不確定你在這裏需要子容器。根據我在帖子中看到的內容,應該有可能用所需的所有配置「建立」一個容器。 [如果這個假設是不正確的,這將有助於解釋爲什麼和你遇到的問題。]

子容器通常用於當你想保留原始容器並使用它的大部分設置,但有一些配置差異例如單身人士的生活時間並不是真正的全球單身人士,而只限於兒童容器。

基於上述,我認爲你應該能夠與每個ConfigureContainer()配置一個容器,覆蓋在以前的配置具體配置:

protected override void ConfigureContainer(IUnityContainer container) 
{ 
    if (container == null) 
    { 
     throw new ArgumentNullException("container"); 
    } 
    // Load default container 
    container.LoadConfiguration(); 
    container.AddExtension(new ConfigExtension()); 

    // Load child configuration on top of first configuration 
    container.LoadConfiguration(ConfigurationManager.AppSettings["ChildUnityContainer"]); 
} 

在此之後運行默認配置和子容器應加載。例如,如果配置是這樣的:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <container> 
     <register type="IDoctor" mapTo="Doctor" /> 
     <register type="IDoctor" mapTo="EyeDoctor" name="eye"/> 
    </container> 
    <container name="Child"> 
     <register type="IDoctor" mapTo="EyeDoctor"/> 
    </container> 
    </unity> 

呼叫LoadConfiguration()LoadConfiguration("Child")容器將具有2名註冊後:IDoctor映射到EyeDoctor(這將覆蓋在默認容器中的第一登記)和IDoctor名稱爲「眼「映射到EyeDoctor(現有註冊在第二次LoadConfiguration調用後保留)。