Adding Dagger2 to Android

Dagger2 is a powerful dependency injection library. However, it can be confusing for the first-time user. And unless things are created in the correct order, builds fail with cryptic error messages.

I could never remember the order of the steps required to add Dagger to an android project. So I wrote a project from scratch to document the process.

Project Setup

  1. Setup Gradle version variables (optional)
  2. Setup Gradle dependencies
  3. Create an App class that extends Application
  4. Add Timber logger initialization to App.onCreate() (optional)
  5. Add App to manifest
  6. Create any classes that will be injected by Dagger2
  7. Create any classes that will @Inject objects using Dagger2 (use constructors but don't use @Inject yet)
  8. Add UI implementation
  9. Compile and run the code.

Dagger Packages

  1. Create the following packages for Dagger2
    • di.builder
    • di.component
    • di.module

Dagger Modules

  1. Create AppModule.kt in di.module
  2. Create AppModule.kt in di.module

Dagger Builders

  1. Create ActivityBuilder.kt in di.builder
  2. Create any other builders as needed

Dagger Components

  1. Create AppComponent.kt in di.component

Extend Activity class(es)

  1. MainActivity now extends DaggerAppCompatActivity

Rebuild

  1. Rebuild the app

Extend App class

  1. App now extends DaggerApplication
  2. Add required override for applicationInjector() (verify DaggerAppComponent exists at this point)

Add Injections

  1. Add any constructor or object injections using @Inject
  2. Add any constructor or object injections using @Inject

Rebuild

  1. Rebuild/run the app

comments powered by Disqus