Advanced Dagger 2 Tutorial For Android- (Dependency Injection Framework)

What is need of Dependency Injection?

Dependency Injection is built upon the concept of Inversion of Control. Which is a class should get its dependencies from outside, means no class should instantiate another class but should get the instances from a configuration class.

If we create an instance of another class via the new operator, then it cannot be used and tested independently from that class and is called tight coupling which is not good programming practice.

What is Dagger 2?

Dagger 2 is dependency injection framework. It is based on the Java Specification Request (JSR) 330. is arguably the most used Dependency Injection, or DI, framework for Android.

Pro Tip: You should think of Dagger not as a Dependency Injection framework but as a code generator tool that need to know how to create instances of certain classes. Then you, as a developer, tell Dagger how to build and connect them.

Dependency Injection Types:

  1. Constructor Injection: Injecting the method parameters.
  2. Field Injection: Injecting the member variable (must not be private).

Dagger 2 uses the following annotations:

  • @Module and @Provides: define classes and methods which provide dependencies.
  • @Inject: request dependencies. Can be used on a constructor, a field, or a method.
  • @Component: enable selected modules and used for performing dependency injection.
  • @Singleton: annotation to indicate that there should be only one instance of the object.

1).Defining Object providers (Dependency Providers):

Dependency Injection context is typically used to define the set of objects which can be injected.

In Dagger 2, classes annotated with @Module are responsible for providing objects which can be injected. Such classes can define methods annotated with @Provides. The returned objects from these methods are available for dependency injection.

2). What is Object Consumer(Dependencies)?

The @Inject annotation used to define a dependency. If you annotate a constructor with @Inject, Dagger 2 can also use an instance of this object to fulfill dependencies. This was done to avoid the definition of lots of @Provides methods for these objects.

3). What is Component Connector?(Connecting Consumer and Producer)

The @Component Annotation is used on an interface. Such an interface is used by Dagger 2 to generate code. The base pattern for the generated class is that Dagger is used as prefix followed by the interface name. This generates class has a create method which allows configuring the objects based on the given configuration. The methods defined on the interface are available to access the generated objects.

4)Scope Annotations(@Singleton)

The @Singleton Annotation to indicate that there should be only one instance of the object.