joydip_kanjilal
Contributor

How to implement DI in WebAPI using NInject

opinion
Apr 21, 20174 mins
Software Development

NInject is a popular IOC container that can be used to inject dependencies in your WebAPI controllers easily

ninject
Credit: IDG

Dependency injection is a software design pattern that helps you to build pluggable implementations in your application using loosely coupled, testable components. It eliminates the hard-coded dependencies between the types and makes your types easier to build, test, and maintain over time. The IOC (Inversion of Control) design pattern states that objects should not create objects on which they depend in order to perform some activity.

You have many IOC containers that help you in automatic instantiation and life cycle management of the objects. Note that Dependency injection is a subset of the IOC principle. The IOC containers leverage dependency injection to invert the flow of control.

Getting started

To get started with this implementation create a new WebAPI project in Visual Studio. Next, install the necessary packages from NuGet to work with NInject. You can install the Ninject.Web.WebApi.WebHost package via the NuGet Package Manager. This would in turn install the following two packages for you.

Ninject.Web.WebApi

Ninject.Web.WebApi.WebHost

Dependency injection using NInject

Once the Ninject.Web.WebApi.WebHost package is successfully installed, the NInject.WebCommon.cs file is automatically created inside the App_Start folder in your project. There would be a lot of boilerplate code generated – just ignore it and refer to the RegisterServices() method. At first glance, here’s how this method would look like.

private static void RegisterServices(IKernel kernel)

{

}

You would need to write your code in the RegisterServices method to register the services or inject the dependencies. We will come back to this later in this article.

In this example, we will be using constructor injection – a type of dependency injection in which one or more dependencies are injected through constructors. The other two types of dependency injection include: setter injection and interface injection. I covered this in detail in one of my earlier posts.

As a next step, create a new controller named AuthorsController to the WebAPI project you have created. Replace the default code of the AuthorsController with the one given below.

public class AuthorsController : ApiController

    {

        private readonly IAuthorRepository repository;

        public AuthorsController(IAuthorRepository repository)

        {

            this.repository = repository;

        }

        public List<string> Get()

        {

            return repository.GetAllAuthors();

        }

    }

The AuthorsController contains a readonly reference to the IAuthorRepository interface, an argument constructor and a Get action method. Note that the AuthorsController uses a constructor to inject the dependency, i.e., it is an argument constructor that accepts a reference to the IAuthorRepository interface as a parameter. The IAuthorRepository interface is implemented by the AuthorRepository class. Here’s how the IAuthorRepository interface looks like.

public interface IAuthorRepository

    {

        List<string> GetAllAuthors();

    }

The GetAllAuthors() method is used to return a list of authors. The author names are hard-coded. The AuthorRepository class implements the GetAllAuthors method as shown below.

public class AuthorRepository : IAuthorRepository

    {

        public List<string> GetAllAuthors()

        {

            List<string> authors = new List<string>();

            authors.Add("Joydip");

            authors.Add("Pete");

            authors.Add("Steve");

            return authors;

        }

    }

Registering our services with Ninject

This step is quite simple. Remember we discussed the RegisterServices method earlier? This belongs to the static class NinjectWebCommon in the NinjectWebCommon.cs file. Here’s how you can use the RegisterServices method to resolve the dependencies.

private static void RegisterServices(IKernel kernel)

{

   kernel.Bind<IAuthorRepository>().To<AuthorRepository>();   

And that’s all you need to do. If you see any runtime errors that are related to NInject, that may be due to ActivationException. To fix it, you should install the latest version of Ninject.Web.WebApi package. Just upgrade the Ninject.Web.WebApi again, recompile and then execute your application again.

You can take a look at this post for additional information on how we can use NInject with WebAPI.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author