簡體   English   中英

來自xml的Ninject依賴項綁定

[英]Ninject dependency binding from xml

如你所知,Ninject內核綁定就像這樣。

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

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

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

我可以在代碼中獲取此字符串。 但我怎么能用它呢

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

或者Niniject可以支持默認值嗎?

您可以使用非泛型To(Type)重載。

從app.config獲取類型:

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

使用類型:

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

所有人都說,請理解Ninject鼓勵您在代碼中配置綁定,而不是依賴配置文件。

我沒有在我的任何項目中使用它,但也許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文件中。

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文件的Copy to Output Directory屬性設置為Copy for new,以便可以將其自動復制到輸出目錄

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

最后得到解決方案不要忘記將此文件的xml文件的Directory屬性的Copy to Output設置為Copy for new,以便可以將其自動復制到輸出目錄。 更多

你可以試試:

Bind<IClientChannelFactory<ICustomerServiceChannel>>()
  .To<ClientChannelFactory<ICustomerServiceChannel>>() 
  .WithConstructorArgument("endpointConfigurationName", ServiceBinding);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM