Dagger Introduction - SatanPandeya/Dagger-2.0-Demo GitHub Wiki

Dagger

Understanding Dependency

When we have an object that needs or depends on another object to do it's work, this is dependency.

Whenever a class A uses another class or interface B, then A depends on B. A cannot carry out its work without B, and A cannot be reused without also reusing B. In such situation, the class A is called the "dependent" and class or interface B is called "dependent".

Dependencies are bad because they decrease reuse.

Dagger 2

Setup

Step 1

We need to modify the project's build.gradle file as shown:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
   dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    // the latest version of the android-apt plugin
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
   }
 }

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots/'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Step 2

Open build.gradle in project's app folder and modify as follow:

apply plugin: 'com.neenbedankt.android-apt'

dependencies{
// apt command comes from the android-apt plugin
    compile 'com.google.dagger:dagger:2.0.2'
    apt 'com.google.dagger:dagger-compiler:2.0.2'
    provided 'org.glassfish:javax.annotation:10.0-b28'
}

Dagger 2 API

Dagger 2 provides number of special annotations:

  • @Module: For those classes whose methods provides dependencies
  • @Provides: For the methods within @Module classes
  • @Inject: Request a dependency(a constructor, a field, a method)
  • @Component: Bridge between modules and injection

Dagger 2 Workflow

To implement Dagger 2:

  • Identify the dependent objects and its dependencies
  • Create a class with the @Module annotation, using the @Provides annotation for every method that returns a dependency.
  • Request dependencies in your dependent objects using the @Inject annotation.
  • Create an interface using the @Component annotation and add the classes with the @Module annotation created in the second step.
  • Create an object of the @Component interface to instantiate the dependent object with its dependencies.

References: