Ninject kernel binding is like this as you know.
kernel.Bind<IMyService>().To<MyService>();
I want to get MyService from xml. WebConfig or App.Config like this.
<add key="service" value="MyNamespace.MyService">
I can get this string in code. But How can I use it
kernel.Bind<IMyService>().To<???>();
Or can Niniject support this as default?
You can use the non-generic To(Type)
overload.
Get type from your app.config:
string service = ConfigurationManager.AppSettings["service"];
Type serviceType = AssemblyContainingYourType.GetType(service);
Use the type:
kernel.Bind<IMyService>().To(serviceType);
All said, please understand that Ninject
encourages that you configure bindings in code and don't rely on configuration files.
I didn't use it myself in any of my projects, but maybe the Ninject xml extension might be helpful.
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>
Not sure though, if you can store it in a App.config file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With