Skip to content

Instantly share code, notes, and snippets.

@alwarren
Last active September 5, 2018 13:18
Show Gist options
  • Save alwarren/dd868f197bbdd40dfc30b9c5a39884f1 to your computer and use it in GitHub Desktop.
Save alwarren/dd868f197bbdd40dfc30b9c5a39884f1 to your computer and use it in GitHub Desktop.
Step-by-step instructions for setting up Dagger2 in an Android Project (Kotlin)

A Step-by-step Process for 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.

These step-by-step instructions were created while setting up a new project 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

10. Create the following packages for Dagger2  
    * di.builder
    * di.component
    * di.module

Dagger Modules

11. Create AppModule.kt in di.module
12. Create activity module(s) in di.module for injecting singletons used by the activity

Dagger Builders

13. Create ActivityBuilder.kt in di.builder
14. Create any other builders as needed

Dagger Components

15. Create AppComponent.kt in di.component

Extend Activity class(es)

16. MainActivity now extends DaggerAppCompatActivity

Rebuild

17. Rebuild the app

Extend App class

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

Add Injections

20. Add any constructor or object injections using @Inject
21. Remove any hard coded method arguments of injected methods

Rebuild

22. Rebuild/run the app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment