Dependency Injection in Android

Let us assume, we want to store some data in SharedPreferences. In order to save or retrieve shared preferences data, we need the instance of shared preference in our Activity’s boilerplate code. And it may lead to problems in testing, managing, etc. if our codebase is large. This is where Android Dependency Injection helps. Here, SharedPreferences acts as a dependency for our Activity so, we don’t create its instance in our activity rather we inject it from some other class. Below is an illustration of the situation.

Dependency Injection with Dagger 2 in Android

If there are two classes, class A and class B and class A depends on class B then class B is called dependent for class A.

So, Every time we want to access class B in class A we need to create an instance of class B in Class A or use static factory methods to access class A. But this will make our code tight coupled, difficult to manage, and test. In order to remove these problems, we use dependency injection. Dependency Injection is a design pattern that removes the dependency from the programming code and makes the application easy to manage and test. It also makes programming code loosely coupled.

Similar Reads

Dependency Injection in Android

Let us assume, we want to store some data in SharedPreferences. In order to save or retrieve shared preferences data, we need the instance of shared preference in our Activity’s boilerplate code. And it may lead to problems in testing, managing, etc. if our codebase is large. This is where Android Dependency Injection helps. Here, SharedPreferences acts as a dependency for our Activity so, we don’t create its instance in our activity rather we inject it from some other class. Below is an illustration of the situation....

Dagger 2

Dagger 2 is a compile-time android dependency injection framework that uses Java Specification  Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are:...