This is a frequent misunderstanding – Why use Dependency Injection when you can ask a factory for your object and have it returned to you?

The answer is that DI does more than just create an object for you. It enables you to delegate the construction of the object, while also preserving information about the type you are trying to create. This is ideal because when you write a test around your class, you can pass in Mock Objects as easily as real objects.

Dependency Injection

Passing in the object that a method  needs as an argument (IAccount account). This way, mock objects could be passed in as easily as real objects.

void CheckingAcct(IAccount account) 
{ 
 account.Open(); 
}

static void Main()
{
     IAccount acct = AccountFactory.CreateAccount();    
     acct.Open();
}

Abstract Factory

void CheckingAccount() // example #1 – Difficult to do mock objects because there is no idea of what the method needs
{
    IAccount acct = AccountFactory.CreateAccount();
    acct.Open();
}

void CheckingAccount(IAccountFactory acctFactory) // example #2 – There is SOME idea of what the method needs, but is not ideal
{
    IAccount acct = acctFactory.CreateAccount();
    acct.Open();
}

Summary

An abstract factory can be used in conjunction with D.I. as shown above. D.I. serves a different purpose and is the chosen method of delineating object creation from actual object usage. This has several advantages in addition to the mock unit testing example shown above. 

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.