繁体   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