Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject dependency binding from xml

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?

like image 659
barteloma Avatar asked Sep 30 '13 11:09

barteloma


2 Answers

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.

like image 125
YK1 Avatar answered Nov 10 '22 01:11

YK1


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.

like image 35
treze Avatar answered Nov 09 '22 23:11

treze