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.
Basically, this allows you to inject a delegate Func
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:
this.unityContainer .RegisterAutoFactoryFor<ICustomer, Customer>() .WithoutParameters(); this.unityContainer .RegisterAutoFactoryFor<ICustomerViewModel, CustomerViewModel>() .WithParam<ICustomer>();