Dependency Injection: Dagger

Ken Baldauf

Senior Software Engineer @ Acorns

Dagger 2

  • Most popular Android DI framework
  • Compile time DI framework for Java
  • Doesn't use reflection
  • Heavy use of annotation processing
  • Lots of generated boilerplate
  • Maintained by Google
    • Based of Square's Dagger 1
  • Hilt: opinionated Dagger extension
    • Standardizes the way Dagger is incorporated into an Android project

Modules & Components

  • Module
    • A provider of dependencies
    • Defines how dependencies are built
  • Component
    • Resolver of dependencies
    • Container that bundles one or more modules together
    • Generates an object graph at compile time
      • Consists of objects it knows how to resolve
        • As well as their dependencies
    • User must manage a Component's lifecycle
    • SubComponents
      • Components that inherit from a Component 

Scopes

  • By default Dagger creates a new instance of an object each time it is requested
  • To avoid that, we can use scope annotations
  • Allow us to persist a single instance of a dependency for a component's entire life
  • Scoped & unscoped dependencies can live in same module
    • Scoped dependencies must live in a component with the same scope
  • No 2 components can be assigned the same scope
  • @Singleton is a predefined scope in Dagger
    • But we can define our own

Provides vs Binds

  • @Provides & @Binds
    • 2 ways to define dependencies in modules
    • Declare type being provided & dependencies needed
    • Can't be used in the same module
  • @Provides
    • Declares exact construction of provided object
    • Useful when constructor injection can't be used
      • Ex: Retrofit's builder pattern
  • @Binds
    • Construction of object is inferred by Dagger
    • Generates less code
    • Maps an interface or generic return type to an implementation

Questions?

Dependency Injection: Dagger

By Kenneth Baldauf

Dependency Injection: Dagger

What do you need to know about using Dagger for dependency injection on Android?

  • 220