No more abstract factory pattern with inversion of control
Published on April 13 2013
Are you using an inversion of control container with the factory pattern to create objects at run time?
You might want to read on to see how to write cleaner code…
We have been using Unity lately at work and I have came across the factory pattern sprinkled around the codebase. Its main usage is due to the polymorphic behaviour of the code, that is, we don’t know what objects we want to create until run-time.
Say if I describe three different types of car as follows:
Ok, so we’ll need a factory to create the cars because we don’t know what tyoe of ICar we want until run-time.
Then I would normally inject the factory into the class via the constructor.
And to finish up, we’ll need to wire up all dependencies using a Unity bootstrapper.
Basically, we have created a factory that creates the Car based on some run-time parameter being set, say a drop down list being selected in a web application, or some data that is passed to a WCF service call, etc.
How about refactoring out the factory? I’ll start by creating the following constructor.
In the bootstrapper I tell Unity how to create the Car objects. That is, by using a function that resolves the ICar based on a name.
There is no need for the factory class now, yeah! When we want to create an ICar we’ll use the Invoke method of the Func.
To me, this is cleaner code, less code == win. I’ve created a sample ASP.NET MVC application using this approach, take a look.