Design Patterns – When to Use Factory Pattern Instead of Dependency Injection

dependency-injectiondesign-patternsfactory

I'm quite inexperienced in design patterns and while I was studying them I got confused about the application of the Factory pattern. Wouldn't DI decouple the classes more than factory would do it? Or would it be overkill to use DI in some situations? I understand DI as a step beyond Factory in decoupling by implementing IoC.

Best Answer

When to use Factory design pattern instead of Dependency Injection?

(Emphasis mine).

Never, as they aren't mutually exclusive. A factory provides an instance of an object according to a set of rules. Dependency injection tells a unit of code what its dependencies are, rather than it asking something for those dependencies. They are both providing decoupling mechanisms, and they compliment one another.

The key is to never use a static factory. Instead decouple the factory implementation from its contract (eg via an interface) and inject the factory into the unit of code that uses it.

So rather than have a method, eg

void Foo()
{
    var someObject = Factory.Create(someConditions);
}

instead, do:

void Foo(IFactory factory)
{
    var someObject = factory.Create(someConditions);
}