lekaha's blog Change the world     Wiki     Blog     Feed

Dagger2 note

Thanks

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:

coffeeapp_object_graph

Components and Modules:

dagger_modules_structure

dagger_modules_structure

dagger_modules_structure

Scopes:

dagger_modules_structure

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:

class diagram

Think about its denpendencis:

Dependency graph again:

dagger_modules_structure

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

comments powered by Disqus