I have a factory to build cars... it a basic factory, it accepts name of a car, looks for all classes that implement ICar
, chooses the correct type based on car name and initializes the car using reflection.
public class CarFactory
{
Dictionary<string, Type> cars;
public ICar CreateInstance(string carName)
{
// choose type of class from all classes that implement ICar
Type t = GetTypeToCreate(carName);
return Activator.CreateInstance(t) as ICar;
}
// some more code...
}
Now, I have a service which uses CarFactory
. What is the right way to initialize CarFactory
in my service?
One solution would be to inject the factory, but Factory Pattern is a form of IoC itself and it feels odd to inject a factory. According to Nikola Malovic:
using factories together with IoC doesn’t make a lot of sense because IoC container is in a sense “universal abstract factory”.
In other words, in my experience any time I thought about adding a factory I ended with much simpler IoC based solution so that’s why I would dare to say that “IoC kill the Factory star"
The above makes total sense to me, though I have not been able to think of a solution to replace my Factory with DI.
So my question is (for those who use factory pattern) how should I initialize it?
To avoid making the question very long, I have used a simplified CarFactory
example in this question. I have posted the complete example here.
As usual, with these kinds of questions, the answer is that It Depends™. It depends on the problem you're trying solve. While this question is tagged with both dependency-injection and inversion-of-control (to a degree the same idea) none of these are goals in themselves, but only a means to achieve a proper goal.
Usually, the goal is decoupling of behaviour. This leads to the first question, then:
Why does CreateInstance
return ICar
instances?
I assume here that ICar
is an interface. Is ICar
polymorphic? Do you have more than one implementation of that interface?
An object named car sounds to me like an Entity, and those should usually not be injected, since they typically represent data, and not behaviour.
For the sake of argument, though, let's assume that ICar
is truly polymorphic.
As shown here, CarFactory
looks deterministic. It's hard to tell, though, because not the entire implementation is shown. If, however, it's referentially transparent, then why does it even need to be initialised?
Couldn't it just be a static function?
public static class CarFactory
{
public static ICar CreateInstance(string carName)
{
// choose type of class from all classes that implement ICar
Type t = GetTypeToCreate(carName);
return Activator.CreateInstance(t) as ICar;
}
// some more code...
}