Dependency Injection
Dependency Injection
What is dependency injection?
Classes often require references to other classes. For example, a Car class might need a reference to an Engine class. These required classes are called dependencies, and in this example the Car class is dependent on having an instance of the Engine class to run.
There are three ways for a class to get an object it needs:
- The class constructs the dependency it needs. In the example above,
Carwould create and initialize its own instance ofEngine. - Grab it from somewhere else. Some Android APIs, such as
Contextgetters andgetSystemService(), work this way. - Have it supplied as a parameter. The app can provide these dependencies when the class is constructed or pass them in to the functions that need each dependency. In the example above, the
Carconstructor would receiveEngineas a parameter.
The third option is dependency injection! With this approach you take the dependencies of a class and provide them rather than having the class instance obtain them itself.
Example of not dependency
Here's an example. Without dependency injection, representing a Car that creates its own Engine dependency in code looks like this:
class Car { private val engine = Engine() fun start() { engine.start() }
}
fun main(args: Array) { val car = Car() car.start()
}

Example of dependency
class Car(private val engine: Engine) { fun start() { engine.start() }
}
fun main(args: Array) { val engine = Engine() val car = Car(engine) car.start()
}

Relates to
Google's Dependency Injection Guide