Dagger2 note
Thanks
- Uncle Bob’s The Clean Architecture
- Fernando Cejas’s Architecting Android…Then clean way?
- Fernando Cejas’s Architecting Android…The evolution
- Fernando Cejas’s Tasting Dagger 2 on Android
- Dagger 2, A New Type of Dependency Injection
Most important notion
While understanding a new knowledge or new things I am used to google it! But first using images search. Sometimes it is helpful to quickly understand by images, figures, diagrams. So while I was understanding Dagger, I got some images that are most important notion for me:
Dependencies graph:
Components and Modules:
Scopes:
How to use
First, please forget what Dagger is and think about your program and Inverse of Control principle (IoC)[https://en.wikipedia.org/wiki/Inversion_of_control]. You may got the dependency must exists in your program. If it is existed we would easily make our code messy or Spaghetti code.
Here is my step:
Try to draw your class diagram:
Think about its denpendencis:
Dependency graph again:
Declaring Dependencies with @Inject
Conventionly, it is given dependencies from the constructor. So add @Inject on your constructor.
class Thermosiphon implements Pump {
private final Heater heater;
@Inject
Thermosiphon(Heater heater) {
this.heater = heater;
}
...
}
Of course Dagger is able to inject dependencies with fields
class CoffeeMaker {
@Inject Heater heater;
@Inject Pump pump;
...
}
## Declaring who will provide dependencies with @Module and @Provides
@Module
class DripCoffeeModule {
@Provides static Heater provideHeater() {
return new ElectricHeater();
}
@Provides static Pump providePump(Thermosiphon pump) {
return pump;
}
}
Thermosiphon is depended Heater, and Heater we can get from provideHeater()
that instantiate a Heater object.
Building the Graph with Component
@Component(modules = DripCoffeeModule.class)
interface CoffeeShop {
CoffeeMaker maker();
}
Here is a diagram version: http://i.stack.imgur.com/4RchJ.png
Be careful of Scope
Here is good reference: http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/
Officail Sample Source: https://github.com/google/dagger/tree/master/examples/simple/src/main/java/coffee
Strongly recommend to see this talk
Source: https://speakerdeck.com/jakewharton/dependency-injection-with-dagger-2-devoxx-2014