By definition, dependency injection promotes loosely coupled, maintainable, and testable code, and using interface and constructor injection we can get the object of the class implementing the interface.
But when we implement factory we create the object based on the passed Type in the factory method Eg:
interface IVehicle
{
int WheelCount();
}
class car : IVehicle
{
int WheelCount()
{ }
}
class bike : IVehicle
{
int WheelCount()
{ }
}
class factory
{
public IVehicle factoryMethod(string type)
{
switch(type)
{
case "bike":
new bike();
break;
case "car":
new car();
break;
}
}
}
in main():
factory obj = new factory();
IVehicle vehicle = obj.factoryMethod("bike");
As we are creating the object by directly instantiating the concrete classes within the factory method.
So does the factory design pattern violate Dependency Inversion Principle?
No, it doesnt.But the way your code is written does violate.
Instead, if you simply modify yur code for Factory class a little, it will adhere to DI principle.
Like this :
}
Inject the instances through Factory class constructor and return them through faxctoryMethod()