2013-09-30 134 views
6

Ninject內核綁定綁定是這樣,你知道的。Ninject依賴從XML

kernel.Bind<IMyService>().To<MyService>(); 

我想從xml獲取MyService。 WebConfig或App.Config這樣。

<add key="service" value="MyNamespace.MyService"> 

我可以在代碼中得到這個字符串。但是,我如何使用它

kernel.Bind<IMyService>().To<???>();

,或者可以Niniject支持此爲默認?

回答

6

可以使用非通用To(Type)超載。從您的app.config

獲取類型:

string service = ConfigurationManager.AppSettings["service"]; 
Type serviceType = AssemblyContainingYourType.GetType(service); 

使用類型:

kernel.Bind<IMyService>().To(serviceType); 

所有說,請大家明白,Ninject鼓勵您配置代碼綁定和不依賴配置文件。

+1

AssemblyContainingYourType? – barteloma

+0

執行'MyNamespace.MyService'的程序集。 – YK1

+1

爲什麼不推薦?它看起來與XML更好,因爲你不必重新編譯你的項目 – Marc

3

我沒有任何我的項目中使用它自己,但也許是Ninject XML擴展可能會有所幫助。

https://github.com/ninject/ninject.extensions.xml/wiki

<module name="myXmlConfigurationModule"> 
    <bind service="MyNamespace.IMyService, MyAssembly" 
      to="MyNamespace.MyServiceImplementation, MyAssembly" /> 
    <bind service="MyNamespace.IMyOtherService, MyAssembly" 
      to="MyNamespace.MyOtherServiceImplementation, MyAssembly" /> 
</module> 

不知道不過,如果你可以將其存儲在App.config文件。

+0

我用這個kernel.Load(「configuration.xml」);但不工作。 – barteloma

+0

xml是怎麼樣的?那錯誤是什麼?什麼沒有奏效? – treze

+0

激活IMyService時出錯 沒有匹配的綁定可用,且類型不可自行綁定。 激活路徑: 1)請給IMyService 建議: 1)確保您已經定義了IMyService 2)如果一個模塊中定義的結合,確保模塊已經加載到內核中的結合。 3)確保你沒有意外創建多個內核。 4)如果使用構造函數參數,請確保參數名稱與構造函數參數名稱匹配。 5)如果您正在使用自動模塊加載,請確保搜索路徑和過濾器正確。 – barteloma

0

最後得到了解決,不要忘記將設置複製到該文件的XML文件目錄屬性的輸出複製如果更新,以便它可以自動複製到輸出目錄。 for more

1

Ninject內核結合是這樣的: -

像下面創建XML: -

<module name="myXmlConfigurationModule"> 
    <bind service="MyNamespace.IMyService, MyAssembly" 
      to="MyNamespace.MyServiceImplementation, MyAssembly" /> 
    <bind service="MyNamespace.IMyOtherService, MyAssembly" 
      to="MyNamespace.MyOtherServiceImplementation, MyAssembly" /> 
</module> 

然後代碼: -

using Ninject; 

    enter code here 

    class ABC 
     { 
      public void CallingMethodUsingNinject() 
      { 
       private IKernel kernel= new StandardKernel(); 
       kernel.Load("yourXmlFileName.xml"); 
       bool ismodule = kernel.HasModule("myXmlConfigurationModule");//To Check The module 
       if(ismodule) 
       {   
       IMyService MyServiceImplementation = kernel.Get<IMyService>(); 
       MyServiceImplementation.YourMethod(); 
       } 
      } 
     } 

一些你可以面對的問題,由於XML文件屬性設置,所以需要改變你的xml文件設置。 激活IMyService時出錯沒有匹配的綁定可用,且類型不可自行綁定。 解決方案: - 不要忘記設置複製到該XML文件的輸出 目錄屬性複製如果更新,以便它可以被複制到 輸出目錄自動

瞭解更多:-read https://www.packtpub.com/sites/default/files/9781782166207_Chapter_02.pdf