[英]Ninject bind two different parameters of same type in Global.asax
我有一個帶有兩個不同控制器的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);
如果我不能使用它來指定輸入,“ WithConstructorArgument”的目的是什么?
好的,所以我找到了解決方案。 但是我不確定這是正確的方法。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.