Dependency Injection in Android with Dagger 2

Dependency Injection in Android with Dagger 2

Dagger’s Power

Dagger 2 is the upgraded version of the original Square’s Dagger, designed for dependency injection(DI) technology for java. DI’s sensational ability is to decouple the dependency relationship between objects, clear the code, and also let developer focus to the functional classes.
In the complex framework & architecture, DI becomes the standard component, like Spring. Similarly, If you wanna write agile and maintainable code in a large and long-term run Android project, Dagger should be an not so bad option.

How to install

The first step always to install Dagger 2, unfortunately, the official documentdid not give any details in Android’s Gradle build environment. Yeah, Dagger is not just for Android, but for any Java Project.
The good news is above website gives the step to step guides, check out the Setup section.
  • In Root build.gradle:
dependencies {
     // other classpath definitions here
     classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
 }
  • apply the plugin in your app/build.gradle:
// add after applying plugin: 'com.android.application'  
apply plugin: 'com.neenbedankt.android-apt'
  • add compile dependencies:
dependencies {
    // apt command comes from the android-apt plugin
    apt 'com.google.dagger:dagger-compiler:2.2'
    compile 'com.google.dagger:dagger:2.2'
    provided 'javax.annotation:jsr250-api:1.0'
}

install Dagger 2.3 & the common puzzles and the solution

If you are using the latest version of Dagger, at this time of writing, it is the 2.3, above setup code did not work well, the compiler running with error:
Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSetMultimap$Builder.putAll(Ljava/lang/Iterable;)Lcom/google/common/collect/ImmutableSetMultimap$Builder;
The solution is just to add apt ‘com.google.guava:guava:19.0’ just above dagger-compiler
The solution for Dagger 2.3:
dependencies {
    // apt command comes from the android-apt plugin
    apt 'com.google.guaua:guaua:19.0'
    apt 'com.google.dagger:dagger-compiler:2.2'
    compile 'com.google.dagger:dagger:2.2'
    provided 'javax.annotation:jsr250-api:1.0'
}

Usage

Again, the boilerplate code worth any tutorial, the key is to use component, module and annotation keywords properly.
Check out the excellent boilerplate code of Ribot team for example.

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp