我有一个带有两个不同控制器的Web应用程序,我使用配置文件作为控制器的输入。之前我只是使用一个配置文件,可以将其绑定到内核,一切都可以正常工作。然而,现在我将使用两个单独的配置文件,需要ninject来了解使用哪个。这是我认为我会做的一个例子。注释掉也是我在配置之前绑定配置所做的事情。
var kernel = NinjectWebApi.Kernel;
//get base dependency instances from the container
var configurationClient = kernel.Get<IConfigurationClient>();
//initialise local dependencies
var config1 = configurationClient.Get(new GetConfigurationByKeyRequest("Config1"));
var config2 = configurationClient.Get(new GetConfigurationByKeyRequest("Config2"));
//bind local dependencies
//This is what I did when I had just one config
//kernel.Bind<IConfiguration>().ToMethod(c => config1.Configuration);
kernel.Bind<IMy1Controller>().To<My1Controller>()
.WithConstructorArgument("config1", config1.Configuration)
.WithConstructorArgument("config2", config2.Configuration);
kernel.Bind<IMy2Controller>().To<My2Controller>()
.WithConstructorArgument("config2", config2.Configuration);
//Set the dependency resolver to use ninject
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
&#34; WithConstructorArgument&#34;的目的是什么?如果我不能用它来指定输入?
答案 0 :(得分:1)
好的,所以我找到了解决方案。但我不确定这是正确的方法。
var kernel = NinjectWebApi.Kernel;
//get base dependency instances from the container
var configurationClient = kernel.Get<IConfigurationClient>();
//initialise local dependencies
var config1 = configurationClient.Get(new GetConfigurationByKeyRequest("Config1"));
var config2 = configurationClient.Get(new GetConfigurationByKeyRequest("Config2"));
//bind local dependencies
kernel.Bind<IConfiguration>().ToMethod(c => config1.Configuration).Named("config1");
kernel.Bind<IConfiguration>().ToMethod(c => config1.Configuration).Named("config1");
kernel.Bind<IMy1Controller>().To<My1Controller>()
kernel.Bind<IMy2Controller>().To<My2Controller>()
//Set the dependency resolver to use ninject
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
要使ninject知道使用哪一个我需要在构造函数中稍微更改签名:
public My1Controller([Named("Config1")] IConfiguration config1)