如你所知,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,以便可以将其自动复制到输出目录。 for more
你可以试试:
Bind<IClientChannelFactory<ICustomerServiceChannel>>()
.To<ClientChannelFactory<ICustomerServiceChannel>>()
.WithConstructorArgument("endpointConfigurationName", ServiceBinding);