In this article, we’re going to set up dependency injection in a new ASP .NET Web API project, using Ninject as our IoC container.
For starters, do the following:
- Create a new Web API project.
- Install the Ninject.Web.WebApi NuGet package.
- Install the Ninject.Web.WebApi.WebHost NuGet package.
Since I need an injectable service to demonstrate this with, I’m also going to install my very own .NET Settings Framework via the Dandago.Settings NuGet package.
When you installed Ninject.Web.WebApi.WebHost, it added a NinjectWebCommon.cs class under the App_Start folder:
Ignore the boilerplate crap and look for the RegisterServices() method. There, you can set up your dependencies. In my case, it looks like this (needs namespace Dandago.Settings):
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind<IConfigKeyReader>().To<AppSettingReader>(); kernel.Bind<IConfigKeyProvider>().To<ConfigKeyProvider>(); }
Great! Now, let’s test it. Find ValuesController and at the following code at the beginning:
private int x; public ValuesController(IConfigKeyProvider configKeyProvider) { this.x = configKeyProvider.Get<int>("x", 5); }
Run it, and we should hit the breakpoint when going to /api/values:
It’s working, and that’s all you need.
In case it wasn’t that smooth, however, here are a couple of things that might have gone wrong.
If you’re getting the above error complaining about not having a parameterless public constructor, then you probably forgot to install the Ninject.Web.WebApi.WebHost package.
If on the other hand you went ahead and installed Ninject.Web.WebApi.WebHost first, that brings in an older version of the Ninject.Web.WebApi package, causing the above ActivationException
. The solution is to upgrade Ninject.Web.WebApi.