Reputation: 2021
I have a web app with two different controllers and I use configuration files as input to the controllers. Earlier I was just using one single configuration file and could just bind that to the kernel and everything would work just fine. Now however I will be using two separate config files and need ninject to understand which one to use. Here is an example of how I thought I would do. Commented away is also what i did to bind the configuration before when I only had one.
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);
What is the purpose of "WithConstructorArgument" if I can't use it to specify an input?
Upvotes: 0
Views: 127
Reputation: 2021
OK, so I found a solution. But I am not sure this is the proper way.
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);
And to make ninject know which one to use I need to change the signature slightly in the constructor:
public My1Controller([Named("Config1")] IConfiguration config1)
Upvotes: 1