Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Everything I found about Dagger 2
Dagger step 1: Add android-apt, dagger 2, dagger2-compiler, and javax annotation to the build.gradle files.
Note that they're not all "compile" dependencies.
Step 2: Add our module. Our ApplicationModule will be able to inject the ApplicationContext to classes that need it.
Step 3: Add our Component.Dagger 2 generates code for each Component you create,
using the file name Dagger(NameOfComponent).
Example: DaggerApplicationComponent.
Components can have multiple modules, in our case we have one.
Step 4: Subclass android.app.Application and set the app to use it in AndroidManifest.xml.
In its onCreate(), build the main component.
Totally guessing here, but this is the rough equivalent of creating the ObjectGraph from which subgraphs will sprout.
Step 5: Add inject methods to our Component interface.
You need to add one inject() for every class that wants to participate in dependency injection.
Notes about Dagger 2:
Injecting into a superclass will not inject dependencies for the subclass.
Injecting into the subclass apparently injects into the superclass.
Notice that I injected OutputActivity.
If I instead put BaseActivity here, and called inject() with an OutputActivity instance,
the function call will work but all the injected fields will be null.
That means, it looks good at compile time but fails at runtime.
Step 6: Inject the hard dependency.
Any "new" operators inside a class are hard dependencies. (Not necessarily all of them have to be injected.)
We can move these into the Modules using the @Provides annotation. See ApplicationModule.java
@Inject it into the class,
but be sure to call the Component.inject() method you added in onCreate(). See OutputActivity.java
Step 7: (Optional, Recommended) Refactor.
Move getApplicationComponent() into the superclass, which is BaseActivity.
I am anticipating that other subclasses will have dependencies that will need injecting at some point.
Additional links:
https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2
http://fernandocejas.com/2015/04/11/tasting-dagger-2-on-android/
https://speakerdeck.com/jakewharton/dependency-injection-with-dagger-2-devoxx-2014
https://www.reddit.com/r/androiddev/comments/38bcgw/need_a_good_tutorial_on_dagger_2/
https://github.com/konmik/konmik.github.io/wiki/Snorkeling-with-Dagger-2
http://stackoverflow.com/questions/27036933/how-to-set-up-dagger-dependency-injection-from-scratch-in-android-project/29943394#29943394
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.