Dependency injection
also known as Inversion of Control, is the idea that you should make required components available for a class, instead of creating them within the class itself. When a class creates an instance of another class via the new operator then it creates a hard dependency on that class. One of the benefits of Dependency Injection (DI) is that components are easier to replace, for example with a mock, when you're testing and they can be tested indepently of other classes. Code reuse is also another huge benifit of DI.
Java Specification Request 330 (JSR330)
is standard for java annotations for describing the the dependencies of a class.
The modes of injection it defines are:
- Constructor Injection: Injecting the constructor parameters
- Field Injection: Injecting the member variables (Fields cannont be private)
- Method Injection: Injecting the metho parameters
Dagger II
Dagger II is the DI library of choice for Android, it generates a depency graph using an annotation processor. An Annotation Processor reads compiled files at build time to generate source code. The classes providing the dependencies are generated at build time using the javax inject package.
A depency consumer asks for a dependency from the dependency provider through a connector.
- Dependency provider: Classes Annotated with
@Moduleare responsible for providing objects which can be injected. Classes with@Providesreturn objects that are available for dependency injection. - Dependency consumer: The
@Injectannotation is used to define a depency. - Connecting consumer and producer: A
@Componentannotated interface defines the connection between the provider adn the dependency which is to be generated.
Limitations of Dagger2:
- Does not automatically inject fields.
- Cannot inject private fields.
- Field injection must define a method in
@Componentinterface which takes the instance of the class in which to inject the member variable.
Setting Up Dagger
in build.gradle
dependencies {
compile "com.google.dagger:dagger:2.11"
annotationProcessor "com.google.dagger:dagger-compiler:2.11"
annotationProcessor "com.google.dagger:dagger-android-processor:2.11"
compile "com.google.dagger:dagger-android-support:2.11"
}