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.
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?
Should I inject it? I feel this is the best solution except that Factory Pattern is a form of IoC itself and I am not sure if it is a good idea to inject a factory into the consumer class?
public class SomeService : ISomeService
{
private CarFactory _carFactory;
public SearchService(CarFactory carFactory)
{
_carFactory = carFactory;
}
// more code...
}
If injection of a factory is a bad idea, should I use static factory? or just instantiate it in the constructor?
Aucun commentaire:
Enregistrer un commentaire