The necessity of dependency injection
We have constantly used the Application
class to create instances of these components and pass them in the constructors of the components one layer above (we created the API and Room instances, then the Repository instances, and so on). What we were doing was a simplistic version of dependency injection.
Dependency injection (DI) is a software technique in which one object (the application) supplies the dependencies of another object (repositories, ViewModels
). The reason for this is to increase the reusability and testability of the code and to shift the responsibility for creating instances from our components to the Application
class.
One of the benefits of DI concerns how objects are created across the code base. DI separates the creation of an object from its usage. In other words, one object shouldn’t care how another object is created; it should only be concerned with the interaction with the other object.
In this chapter...