Dependency injection

Glossary » Dependency injection

Dependency injection means giving an object its instance variables.

— Dependency Injection Demystified,  James Shore

In Object-Oriented programming, dependency injection means giving an object the instance variables it will be using by any means you want (the constructor, a setter method, interface injection, etc).

Code without the dependency injected:

public class Document { 
  private Database myDatabase; 

  public Document(protocol, host, port) { 
    myDatabase = new DatabaseThingie(protocol, host, port); 
  } 

  public void doThings() { 
    ... 
    myDatabase.GetData(); 
    ... 
  } 
}

Code with the dependency injected:

public class Document { 
  private Database myDatabase; 

  public Document(Database useThisDatabase) { 
    myDatabase = useThisDatabase; 
  }

  public void doThings() { 
    ... 
    myDatabase.GetData(); 
    ... 
  } 
}

In the example, the Document without the dependencies injected needs to know how to connect to the database; the one with the dependency injected just use what is passed to it.

The core idea of dependency injection is to allow objects to focus on the things that are important to them. In a way, the object injected with the dependencies is using interfaces instead of concrete implementations, so the injection of dependencies is useful to decoupling the different parts of the system, leveraging its understanding and making testing easier.

More info: