How to set up unity or any other dependency injection with MVC or WebApi

I have split this guide into two sections. The first section is for people who just don't remember which classes to use to set up dependency injection. The other is how to set the dependency injection up without any prior knowledge.

Setting up the dependency resolvers

If you are just looking for a way to set the resolver in a MVC project it can be done in the following way:

var container = new UnityContainer();
DependencyResolver.SetResolver(new Microsoft.Practices.Unity.Mvc.UnityDependencyResolver(container));

For a Web API project it is done in the following way:

var container = new UnityContainer();
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);

They can easily be combined and you can use the same container for both resolvers. The dependency resolver is often set in the global.asax.cs file in the Application_Start method.

Installing unity

The easiest way to install unity - in my opinion - is to use the package manage console. It can be found here in Visual Studio:

Tools > Nuget Package Manager > Package Manager Console

In the package manager console type the following and hit enter:

install-package Unity

Depending on whether you need MVC, WebApi or both, you can run one of the following commands:

install-package Unity.Mvc

install-package Unity.WebAPI

You can find the unity project on github for both MVC and WebApi.

You now have unity installed into your project! I hope this went smooth for you, let me know in the comments down below if it did :)