DEV Community

Discussion on: Explain Dependency Injection (DI) like I am five.

Collapse
 
nestedsoftware profile image
Nested Software • Edited

A simple concrete example (using a vaguely Java/C# pseudocode): You want to save some data to a database. You can do something like this:

public class PetManager {
  public PetManager() {
    _dbConnection = new FancyDbConnection("some_connection_string");
  }
  public void savePet(pet) {
    _dbConnection.save(pet);
  }
}
Enter fullscreen mode Exit fullscreen mode

Your PetManager class is responsible for creating and configuring the database, then uses that connection to save a pet record. With dependency injection, the key idea is that the dependency, which is the database connection in this case, can be passed in to the PetManager class from outside (usually as an interface). So it would look like this:

public class PetManager {
  public PetManager(DbConnection dbConnection) {
    _dbConnection = dbConnection;
  }
  public void savePet(pet) {
    _dbConnection.save(pet);
  }
}
Enter fullscreen mode Exit fullscreen mode

This makes it easier to unit test your PetManager class, since you can pass a test-only version of DbConnection. Also, if your application is running in a container of some kind, you can configure the database connection properties in the container, and then let the container wire up the database connection for you at run time. This gives you additional flexibility for setting up these kinds of external dependencies, which can also help with scalability and performance.