Skip to content

Instantly share code, notes, and snippets.

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 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
@Inject it into the class,
but be sure to call the Component.inject() method you added in onCreate(). See
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:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment