Bring your own DI container to ASP.NET 5 - Unity

Now that we understand some basics of how dependency injection is handled by ASP.NET 5 we are ready to start rolling out our integration components for our container of choice. The process may not that straightforward at times and different containers have their quirks. I believe things will improve when new bits actually go GA and it's likely that containers will receive certain changes to play smooth with the abstraction. Microsoft has already provided sample implementations for some containers such as Autofac and Ninject. Surprisingly there is no for Unity yet. Autofac has already published alpha bit of there own integration.

In this post I’m going to walk you through integrating Unity with ASP.NET pipeline. Sample implementation is just my first take on this and it has its rough edges. I think it was kind of a disclaimer. Note that it’s based on version 1.0.0-beta3 of related components.

Note that we use a simple resolution by type without resolve overrides or named resolutions. This is sufficient for the infrastructure to resolve top level objects such as, for example, controllers. The rest of the tree will be handled by your container and you can use its advanced features.

Scoping with Unity

To implement a lifetime scope in Unity you need two things: child containers and HierarchicalLifetimeManager. Child containers inherit registrations from the parent but they also allow you to specify different extensions. For us it's important that we can dispose a child container at the end of request processing when the service scope is disposed. When you register types with a container and specify HierarchicalLifetimeManager it makes the container track objects it creates. Thus, when we dispose the container it will dispose tracked objects (if they implement IDisposable of course).

Service scope factory receives a top level container as a constructor parameter. It works because the factory itself is resolved from the top level service provider by RequestServiceContainer. Notice the EnumerableResolutionExtension that I add to a child container. I will explain that shortly but first let's have a look at the service scope implementation:

Because it is given a child container the service provider it resolves out of it will encapsulate the very same child container instance. We could have created a service provider directly just as well.

Resolving IEnumerable

Unfortunately Unity can't automatically resolve IEnumerable of type when we register just the type. However, it natively supports resolution of an array of registered types. This is more of a design aspect of Unity. When we register multiple services of the same type with it we have to use named registrations otherwise services that are registered later will overwrite those registered earlier. We can register one and only one unnamed service of a particular type.

To consume all registered services of a type in a component we can make it accept an array of service types. This works out of the box but what if we can't change a component from requiring IEnumerable<T> to requiring an array of T? In this case we can rely on InjectionMember's, ResolvedAll() or adding a registration that would map IEnumerable<T> to T[] (T should be known at registration time).

This will work when it's our code and we know what types we are resolving. But we need to support resolution of IEnumerable of any type that's registered by ASP.NET and any framework that runs on it. We need to enable Unity to resolve IEnumerable as an array and it can be done with an extension. An example of such an extension can be found here and this is exactly what I'm using.

The downside of it is that it uses reflection methods like IsGenericType and GetGenericArguments that are not (yet) supported by .NET Core (I am using beta 3 at the time of writing). Like I said there are quirks and things are in flux now. We need to be aware of that.

Registering service descriptors with Unity

In my previous post I was using Populate extension method to register service descriptors with Unity container. Now it is a good time to look into its implementation.

As with scoped child containers we need to add EnumerableResolutionExtension to the top level container. Note that we also register top level service provider and service scope factory. They are going to be used by the hosting infrastructure. The Register method needs to support all registration types (type, instance, factory) and life time modes (transient, singleton, scoped). In Unity object life time is controlled by the life time manager and we provide an appropriate instance of it with each registration.

Show time

Here comes a major disappointment because I haven't managed to make it work with MVC yet. All services are registered successfully and requests are processed by the pipeline but they never hit a controller. It looks like routing is totally screwed up, both imperative as well as attribute based. I am going to research deeper into the issue and provide an update when I find something out. Also lately hosting and dependency injection packages have undergone refactoring so things might have changed.

Still I am going to test our Unity integration. I'll write up a poor man HTTP endpoint that will have some dependencies it will use to produce the response:

We've got IProductService that we're going to use to get a list of products and ILogger service that we are going to use to output messages to console that will actually allow us to observe different life time modes:

ProductService also requires an instance of ILogger. This will allow us to verify scoped and singleton life time modes as we would expect the same instance of ILogger to be injected in ProductService as well as in the test middleware handler during processing of a single request. We would also expect the same instance to be used for different requests in singleton mode.

We are going to run the test application from the command line to be able to observe messages. Let's quickly add Microsoft.AspNet.Server.WebListener package and the following command to project.json:

As expected each request was using their own single instance of the logger. Note that because we were using HierarchicalLifetimeManager this time scoped containers were tracking instances of the logger and disposed them at the end of their lifetime.