Dependency injection using Dagger 2


In a project with multiple classes, if a class (Class X) is dependent on another class (Class Y), then Class Y is a dependency on Class X.

To access Class Y in Class X, it would be required to instantiate Class Y. This makes the code tightly coupled and difficult to test. To avoid these problems, a design pattern called Dependency Injection is used.

  • What is Dependency Injection?

Dependency Injection is a design pattern in which a class is provided with its dependencies from outside. In technical terms, the class that is dependent on another class is called a client, and its dependency is called a service. The class that injects (provides) the service to the client is called an injector.

In this pattern, the client does not determine the service it is going to use, but it is the injector that determines the service that will be used by the client.

  • What is Dagger 2?

Dagger  2 is a compile-time, fully static framework for dependency injection in Android.

Dagger 2 uses the generated code and is based on annotations. It uses the following annotations : 

  • @Module : It is used over the class which provides dependencies by constructing objects.
  • @Provides : It is used over the function in the ‘Module’ class that will provide the object.
  • @Inject : It is used over the fields/functions/constructors to indicate dependency requests.
  • @Component : It is used over an interface that will connect the client and the service.
  • Types of Dependency Injection : 
  • Constructor injection : In this method, the dependencies of a class are passed to its constructor.
  • Field injection : When using field injection, the dependencies are provided after constructing the class.
  • Advantages of Dependency Injection Pattern : 
  • Dependency injection de-couples the classes and its dependencies.
  • Increases readability and reusability by removing dependency implementations from the client code.
  • It is easier to unit test the client code.

Leave A Comment

Your email address will not be published. Required fields are marked *