Dependency Injection vs Factory Pattern

Binoj Antony picture Binoj Antony · Feb 17, 2009 · Viewed 171.4k times · Source

Most of the examples quoted for usage of Dependency Injection, we can solve using the factory pattern as well. Looks like when it comes to usage/design the difference between dependency injection and factory is blurred or thin.

Once someone told me that its how you use it that makes a difference!

I once used StructureMap a DI container to solve a problem, later on I redesigned it to work with a simple factory and removed references to StructureMap.

Can anyone tell me what is the difference between them and where to use what, whats the best practice here?

Answer

willcodejavaforfood picture willcodejavaforfood · Feb 17, 2009

When using a factory your code is still actually responsible for creating objects. By DI you outsource that responsibility to another class or a framework, which is separate from your code.