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:

  1. Constructor Injection: Injecting the constructor parameters
  2. Field Injection: Injecting the member variables (Fields cannont be private)
  3. 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.

  1. Dependency provider: Classes Annotated with @Module are responsible for providing objects which can be injected. Classes with @Provides return objects that are available for dependency injection.
  2. Dependency consumer: The @Inject annotation is used to define a depency.
  3. Connecting consumer and producer: A @Component annotated interface defines the connection between the provider adn the dependency which is to be generated.
Limitations of Dagger2:
  1. Does not automatically inject fields.
  2. Cannot inject private fields.
  3. Field injection must define a method in@Component interface 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"
}

results matching ""

    No results matching ""