Add Dependency Injection to an ASP.NET MVC application

Add an IoC container to your ASP.NET MVC easily and quickly.

Friday, July 29, 2016

This is a step by step tutorial on how to set up DI on a new ASP.NET MVC application. It is assumed that you already have knowledge of how to create an ASP.NET MVC project.

Right-click on project and select to manage nuget dependencies. Then search for Castle Windsor (or feel free to choose another IoC container):

Select Castle Windsor MVC bootstrapper nuget package

Most of the work has been done for you. The dependency graph that is generated for a particular request is started in the controller as that's where the framework gives control to the developer so an implementation of IWindsorInstaller is created automatically which registers all controllers.

Controllers castle windsor installer

Also a custom controller factory is also created. The reason for this is that the default controller factory tries to create instances of the controllers using a parameterless constructor (with no dependencies injected) but we are trying to have the dependencies injected, aren't we?

Windsor controller factory

After this is done you could try to put a dependency in a constructor but you'd end up with an exception as the IoC container doesn't yet know what implementation to pass in the constructor.

Dependency not registered in IoC container

The following is an example of how to register that service. Like in the controllers installer, we create a ServicesInstaller class which implements IWindsorInstaller. The IoC looks for these types wherever they are in your application and take care of executing them.

Services installer

In this example, I chose a convention to register my UserService but also any class that is compiled in the same Services namespace. When a new class is added to that namespace it will also be automatically registered. Because we should normally be programming against abstractions, part of my convention also registers the implementations with their first interfaces.

Also take into account the lifestyle chose for my services: unique per web request. This will make sense if its dependencies also have such a lifestyle. If a dependency were to have a shorter lifestyle like transient, this would not be a good idea though as its transient dependencies would not be instantiated more often if your service is only instantiated once per web request.

And voilá, the dependencies are automatically added:

Injected service