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?
bikeandcarto live in a referenced assembly. If, on the other hand, the factory is hidden behind an abstraction, it allows you to move both the factory and the vehicle implementations to an unreferenced assembly, which could even be loaded dynamically as a plugin. In that case the consumer is decoupled from the implementations, even though it uses a"car"key. The implementation can still be changed.