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.