Dependency Injection in Web API

Avishek Patra
5 min readAug 15, 2015

Hey everyone

So today we are going to learn “How to implement dependency injection in Web API”.

Before we begin first we have to know what is a Restful service.

REST is the acronym of Representational State Transfer ( REST) which is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. You can catch up the following link for further on this.

Before I begin I believe that the reader have the knowledge on Web API and basic on HTTP protocol.

What is dependency injection and what is an IoC? Are they same or entirely different? Dependency injection is an architectural pattern which basically helps to create loosely coupled layers. Say you have an business layer which computes some business operations and another presentation layer which displays the business output. Now if you don’t create two separate layer instead put them in the same physical box then your application might run but if you want change your presentation layer to a different technology then you have to rewrite the entire business layer which calls a huge set of testing and time consuming and that entirely misses the flavor of re-usability. So dependency injection is the technique through which we actually create the layered loosely coupled architecture, and we can put change any of the layer without affecting the other layer.

Dependency Injection are varied from two types “Constructor Injection” and “Setter Injection”. Here in this article we will be using CI with the IoC Container Microsoft Unity. I’ll explain the purpose of IoC later of this post.

First we will be creating an empty ASP.Net MVC 5 application. Once you create that you’ll get the following folder structure in your solution explorer. Here my project name is RESTFramework.

Next we have to create a web api controller, so lets start by creating one with the name “ProductController.cs”, remember to select an empty controller. So once we are done with that then we have to add an IoC (Inversion of Control) for this project. For this example we will be using Microsoft Unity.

Lets install it by running the command “ Install-Package Unity.AspNet.WebApi -Version 3.5.1404″ in package manager console.

Once you’re successfully done with the installation you can see the following files and the references are added in your solution.

So you can see that the references like Microsoft.Practices.Unity, Microsoft.Practices.Unity.Configuration, Microsoft.Practices.Unity.WebApi.

Now if you expand the App_Start Folder then you can see UnityConfig.cs which is the main container of our Ioc.

Once you open the file UnityConfig.cs in your code window you can see the following function

/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name=”container”>The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();

// TODO: Register your types here

This is the main container through which you’ll be registering the dependencies.

Now lets add a folder called “Services”. Inside the file create and interface named IProductRepository.cs and ProductRepository.cs

So from the naming convention you can understand that IProductRepository.cs will be implemented by ProductRepository.cs

Lets decorate the interface something like this

I have already created a model class called Products. In ProductRepository.cs implement the interface like this way.

public class ProductRepository : IProductRepository
{
public Products GetProducts()
{
return new Products { ProductId = 1, ProductCode = “IIS9899”, ProductName = “Beer”, ProductDescription = “This is cool!!!” };
}
}

Now we will be calling this business layer from our presentation layer. So we will be calling this interface, yes interface since we will be using dependency injection to make both layers loosely coupled, so we will be adding the following lines of code in our ProductsController.cs

Lets create the controller something like this.

public class ProductController : ApiController
{
private readonly IProductRepository _productRepository;

//Adding Constructor Injection
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}

So it seems like we are all done lets execute the application and hit the url. If you’re very new with web api then as per web api routing technique the url will be “<server-name>:<port-number>/api/product”

Damn!! an error gonna come saying something like “An error occurred when trying to create a controller of type ‘ProductController’. Make sure that the controller has a parameter less public constructor.”

Now the role of IoC comes into play. lets open the UnityConfig.cs file and add the following lines in RegisterTypes method

container.RegisterType<IProductRepository, ProductRepository>();

The above line is actually mapping between your repository interface and class and which is evaluated during the load of the web api controller and if all the maps are correctly defined then the controller will execute properly and will give you appropriate output.

So after adding that line execute your project and you can see and out put something like

You can get the codes from GITHUB .

In my next article we will discuss on Injecting AutoMapper through dependency Injection and making it highly loosely coupled from each other.

Originally published at http://coderera.wordpress.com on August 15, 2015.

--

--