comment 0

An Automatic Factory for the Unity Container (with respective NuGet package :-) )

UPDATE: I recently created an improved version of this idea, in which you are allowed to specify a factory interface, and my framework will automatically tell Unity how to generate an implementation of that factory interface.

In the middle of the last sprint of the software project we’re just starting, we had the need for some object factories. Out of the sense of urgency/lack of immediate solutions, we started writing them by hand.

I knew we wouldn’t go far down that road, as that would require writing unit tests for each factory, and as a result, too much boilerplate code.

In the following inter-sprint period, I took the opportunity to look for a simpler solution, preferably one which would be a drop-in replacement. I am aware that other IoC containers such as Castle Windsor already provide this type of functionality through the Typed Factory Facility, but not of anything similar in Unity.

The research that ensued brought to my attention a new functionality present in Unity since version 2.0, called delayed resolution (achieved through the new InjectionFactory class).

Basically, this allows you to inject a delegate Func which when executed causes a Resolve() call to be done on the container. This by the way, is a much better way to achieve delayed resolution than the well-known ServiceLocator code smell (notice I didn’t call it an anti-pattern), by keeping your dependencies explicit.

The use of this approach to build a simple factory is described in this StackOverflow post. In order to consume this in our project, and by extension, to the masses, I adapted the example to also allow parameters to be passed to the factory method:

    .RegisterAutoFactoryFor<ICustomer, Customer>()
    .RegisterAutoFactoryFor<ICustomerViewModel, CustomerViewModel>()

You can check out the project source at GitHub, and the resulting NuGet package at the official NuGet feed.