Reading Ninject WithConstructorArguments from Web.config

I have the following RegisterServices function:

private static void RegisterServices(IKernel kernel) { kernel.Bind<ISearchRepository>().To<SearchRepository>(); kernel.Bind<ITagRepository>().To<TagRepository>(); kernel.Bind<IStore>().To<Store>() .WithConstructorArgument("dbId", ConfigurationManager.AppSettings["DatabaseId"]) } 

Using breakpoints, I can confirm that the ConfigurationManager fills the value correctly.

However, on startup, I get the following exception when the kernel completes the binding:

enter image description here

If I replace the ConfigurationManager link with a constant, the application works fine.

I do not want to lose the ability to configure Ninject through the configuration file, is this a Ninject limitation?

+4
source share
1 answer

No, there is no such Ninject restriction.

I assume the problem is that ConfigurationManager.AppSettings["DatabaseId"] returns string , and your dbId argument is of type int (or some other non-string type).

Try:

 var databaseId = Int32.Parse(ConfigurationManager.AppSettings["DatabaseId"]); kernel.Bind<IStore>() .To<Store>() .WithConstructorArgument("dbId", databaseId); 
+3
source

All Articles