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
- Setup Gradle version variables (optional)
- Setup Gradle dependencies
- Create an App class that extends Application
- Add Timber logger initialization to App.onCreate() (optional)
- Add App to manifest
- Create any classes that will be injected by Dagger2
- Create any classes that will @Inject objects using Dagger2 (use constructors but don't use @Inject yet)
- Add UI implementation
- Compile and run the code.
Dagger Packages
- Create the following packages for Dagger2
- di.builder
- di.component
- di.module
Dagger Modules
- Create AppModule.kt in di.module
- Create AppModule.kt in di.module
Dagger Builders
- Create ActivityBuilder.kt in di.builder
- Create any other builders as needed
Dagger Components
- Create AppComponent.kt in di.component
Extend Activity class(es)
- MainActivity now extends DaggerAppCompatActivity
Rebuild
- Rebuild the app
Extend App class
- App now extends DaggerApplication
- Add required override for applicationInjector() (verify DaggerAppComponent exists at this point)
Add Injections
- Add any constructor or object injections using @Inject
- Add any constructor or object injections using @Inject
Rebuild
- Rebuild/run the app