5 Dagger 2 (DI in Android) - G00fY2/android-mvp-wiki GitHub Wiki

5 Dagger 2 (DI in Android)

Dagger 2 is an Dependency Injection framework for Android. It is based on annotation-based code generation and was first developed by Square. Version 2 of Dagger was developed in cooperation with Google. Dagger 2 works with any Java project but has a specific focus on Android.

5.1 Classes

ApplicationModule (@Module)

  • this is where Dagger keeps track of the dependencies
  • Provider of dependencies are defined with @Provides annotation
  • @Singleton indicates that Dagger should create an instance only once per application (other scopes possible)

ApplicationComponent (@Component)

  • injector class
  • Modules that provide dependencies must be listed in the annotation
  • tells Dagger where the dependencies will be injected
  • assigns references in Activities, Services or Fragments to have access to the defined dependencies
  • activities, services or fragments that are allowed to request the dependencies declared by the modules should be declared in this class with individual inject() methods

Instantiating the component

  • to declare the instances only once we need to extend the application class
  • here is where Dagger "lives" over the lifetime of the application
  • in this custom application class we build the private dagger component instance in the onCreate
  • provide public getter method for the application component
  • depending on the requirements it can be handy to split the component into application and activity component