Dependency Inversion vs Dependency Injection

Tags: Dependency Injection

It can be confusing get the actual definitions of these terms straight in your head.  Dependency Inversion and Dependency Injection are related but mean different things, let’s discuss.

Dependency Inversion

Dependency Inversion is one of the five SOLID principles of object oriented design.  It’s the ‘D’ principle.  The dependency inversion principle states that:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.

Here’s a more long winded description of what that means.  Say you have a business class BizClass that performs some calculations on some data.  The data come from a repository class.  Rather than having the Repository business class depend on a particular repository, it can depend on a repository interface – IRepository.  That way it can get its data without being aware of what type of repository it’s using.  It could be a repository that gets data from a database -DatbaseRepository, or one that gets it from a flat file FlatFileRepository, etc.  So the high level module (business class) depends on the abstraction IRepository.  And the low level modules (DatbaseRepository , FlatFileRepository) depend upon the abstraction IRepository.

So what about Dependency Injection?

Dependency Injection

Dependency Injection is a method for implementing Dependency Inversion.  It is how one object acquires a dependency.  A commonly used method for acquiring dependencies is constructor injection.  The constructor would look like this:

public BizClass(IRepository repository)

And the client would pass in the repository when creating the BizClass like this:

IRepository repository = new DatbaseRepository();
BizClass bizClass = new BizClass(repository);

What about Inversion of Control?

Inversion of Control

Inversion of Control is a pattern used to implement Dependency Inversion.  Dependency Injection follows the Inversion of Control pattern; it’s one way to do Inversion of Control.

Read more about IoC and DI

No Comments

Add a Comment