Introduction
Dagger is a Dependency Injection tool used to manage dependencies in Android Development.
Advantages of DI are it makes it easy to:
- Reuse
- Testing
- Refactoring
Basic Terms and Usage:
- @Inject
- When @Inject is annotated on a class constructor, it’s telling Dagger how to provide instances of that class.
- When it’s annotated on a class field, it’s telling Dagger that it needs to populate the field with an instance of that type.
- @Component
- An interface annotated with @Component will make Dagger generate code with all the dependencies required to satisfy the parameters of the methods it exposes.
- @SubComponent
- Subcomponents are components that inherit and extend the object graph of a parent component. Thus, all objects provided in the parent component will be provided in the subcomponent too.
- @Module
- Tells Dagger how to provide instances of a certain type.
- @Binds
- Tells Dagger which implementation it needs to use when providing an interface.
- @BindsInstance
- Tells Dagger that it needs to add that instance in the graph and whenever Context is required, provide that instance.
Implementation
- Dagger creates the application graph that lives in the application class. And it stays in memory as long as the application is running. So the graph is tied to the application lifecycle.
- When using Activities, inject Dagger in the Activity’s onCreate method before calling super.onCreate to avoid issues with fragment restoration. In super.onCreate, an Activity during the restore phase will attach fragments that might want to access activity bindings.
- When using Fragments, inject Dagger in the Fragment’s onAttach method after calling super.onAttach.
- Dagger-injected fields cannot be private. They need to have at least package-private visibility.
- Scoping a type to a Component means that the same instance of that type will be used every time the type needs to be provided.
- Scoping rules:
- When a type is marked with a scope annotation, it can only be used by Components that are annotated with the same scope.
- When a Component is marked with a scope annotation, it can only provide types with that annotation or types that have no annotation.
- A subcomponent cannot use a scope annotation used by one of its parent Components.