来自xml的Ninject依赖项绑定

bar*_*oma 6 c# dependency-injection ninject c#-4.0

如你所知,Ninject内核绑定就像这样.

kernel.Bind<IMyService>().To<MyService>();
Run Code Online (Sandbox Code Playgroud)

我想从xml获取MyService.像这样的WebConfig或App.Config.

<add key="service" value="MyNamespace.MyService">
Run Code Online (Sandbox Code Playgroud)

我可以在代码中获取此字符串.但我怎么能用它呢

kernel.Bind<IMyService>().To<???>();

或者Niniject可以支持默认值吗?

YK1*_*YK1 6

您可以使用非泛型To(Type)重载.

从app.config获取类型:

string service = ConfigurationManager.AppSettings["service"];
Type serviceType = AssemblyContainingYourType.GetType(service);
Run Code Online (Sandbox Code Playgroud)

使用类型:

kernel.Bind<IMyService>().To(serviceType);
Run Code Online (Sandbox Code Playgroud)

所有人都说,请理解,Ninject鼓励您在代码中配置绑定,而不是依赖配置文件.