ASP .NET Web API Dependency Injection with Ninject

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:

  1. Create a new Web API project.
  2. Install the Ninject.Web.WebApi NuGet package.
  3. 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:

ninjectwebapi-ninjectwebcommon

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:

ninjectwebapi-breakpointhit

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.

ninjectwebapi-parameterless-constructor

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.

ninjectwebapi-activationexception

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.

2 thoughts on “ASP .NET Web API Dependency Injection with Ninject”

  1. I really appreciate this extremely useful example, however I am new to Web Api 2 and I noticed that there was no formal registering of the dependency resolver that I could see. Not in the WebApiConfig.cs or in the Global.asax like I am used to?

    1. I don’t know how you’re used to doing it, but I think it’s all in NinjectWebCommon. There are two assembly directives that refer to Start() and Stop() methods within the same file, taking care of setup and teardown. I don’t know how this relates to dependency resolvers though.

Leave a Reply to Gigi Cancel reply

Your email address will not be published. Required fields are marked *