Getting Unity Dependency Injection Working with ASP.NET 4.5.1

There are a lot of articles and blog posts out there about how to get Unity working with ASP.NET. After all of those, I found the best reference for doing this was the MSDN Unity documentation. However, there are a few things that you have to change in order to get it working with ASP.NET 4.5.1.

Here is a page on MSDN that describes what to do:

However, in order to make this work, you will need to change the following lines in Web.config (in the element):

... other HTTP modules defined here

To use the following:

This will load the correct HttpModule that will perform the dependency injection. This HttpModule is defined on this page:

Don’t forget to follow all of the steps in the above document. This includes a link to the code for extending HttpApplication to allow you to retrieve the container.

I am also using Unity dependency injection with a WebAPI that is also in this project. I am using the same custom resolver with this, so I have created a Module that contains a public method for setting up the dependencies:

Module UnityRegistrationModule Public Sub RegisterTypes(ByRef container As IUnityContainer) container.RegisterType(Of ITestDtoRepository, TestRepository)(New HierarchicalLifetimeManager()) End Sub End Module

I can then call this method from the two places where dependencies need to be set up. That gives me a single place for setting up dependencies. In VB.NET, this is a module, this could be done in C# as a static method on a public Utility class.

Here is my WebAPIConfig that calls this method…

Public Module WebApiConfig Public Sub Register(ByVal config As HttpConfiguration) ' Web API configuration and services ' Set up dependency injection with Unity Dim container As New UnityContainer() RegisterTypes(container) config.DependencyResolver = New UnityResolver(container) ' Web API routes config.MapHttpAttributeRoutes() config.Routes.MapHttpRoute( name:="DefaultApi", routeTemplate:="api/{controller}/{id}", defaults:=New With {.id = RouteParameter.Optional} ) End Sub End Module

I had a little trouble getting all of this to work because my custom HttpModule was not executing. This is because I did not have it configured in the Web.Config correctly. After some messing around with the namespaces and project name, I was finally able to get it working.

Here is some code that uses a dependency from within a web page (the page has a label on it named “lblTest1”):

Public Class Default Inherits Page _ Public Property _repository As ITestDtoRepository Protected Sub PageLoad(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load lblTest1.Text = _repository.GetAll(Function(x) x.Id = "5c577a7a-13c4-4391-ab80-8ff567274d2e").SingleOrDefault().Description End Sub End Class

As you can see, once you get the configuration correct, using dependencies from within an ASP.NET page is easy. Now, I can simply add a public property to the page of the desired interface and the DI resolver will inject an instance of it for me at runtime. All I have to do is code to the interface. If the required class changes in the future, all I have to do is associate the new class with the interface in the RegisterTypes() method. This is the beauty of dependency injection. I’m completely sold on this idea.

It took me a while to fully grasp the importance of DI, but now that I have, I can’t imagine life without it.