• What is Dependency Injection?

    The term “Dependency Injection” or in short “DI” is independent of Android. It is a design pattern in Software Engineering.

    Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture.

    Implementing dependency injection provides you with the following advantages:

    • Reusability of code
    • Ease of refactoring
    • Ease of testing

    What is Dependency?

    Consider the following Java class.

    public class User{

    private Database mDatabase;

    public User(){

    mDatabase = new Database();

    }

    }

    n the above class, we are creating the object of class Database inside the constructor of class User. So here, we can say that; the User is dependent on the Database. So here, the Database is a dependency for the class User.

    What is Injection?

    As we have seen the User is Dependent on the Database, now think about how the User can get its dependency, which is the Database.

    Dependency Injection is built upon the concept of Inversion of Control. That means a class should get its dependencies from outside.
    In simpler words, your class cannot instantiate another class using a new keyword inside it. Instead, you have to supply the object from outside.

    So let’s discuss DI in the context of Android Application Development.

    Consider a simple application, where we are fetching some data from a web server; let’s say a list of products (containing product title, product images, product price, etc.). And then we are displaying the data in our android application. 

    Assuming we are using Retrofit for the network request and Glide for loading images. See the following diagram.

    As you can see in the diagram, we have many dependencies. Now our task here is to follow the Dependency Injection here in the app to make everything easier. And for this, I am going to use a framework called Dagger 2.

    If you are not aware then, Dagger 2 is now maintained by Google, and it is the most popular Dependency Injection framework available for Android and Java.

    Popular Android Dependency Injection Frameworks

    • Dagger 2

    • ButterKnife

     

     

0 Years in
Operation
0 Loyal
Clients
0 Successful
Projects

Words from our clients

 

Tell Us About Your Project

We’ve done lot’s of work, Let’s Check some from here