2013-09-30 60 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