Dependency Injection using Dagger for Android

Dependency Injection using Dagger for Android

 

Objective: To transform your Android codebase more testable by making static classes as non-static.

Dependency injection is an architectural pattern for loosely coupling software components. Factory pattern is one way to separate the responsibility of creating objects of other classes to another entity.  

When we make use of factory pattern, a factory class, usually can analyze the dependencies of this class. With this analysis it is able to create an instance of the class and inject the objects into the defined dependencies, via Java reflection.

Factory pattern is a tool to implement DI and I have used it to explain the following example:

Example

Consider the following example: CoolClass is a class that is being used by other Fragments & Activities.

Originally CoolClass has a dependency Dep1:

The fragment which uses this class, would have a dependency as follows:

CoolClass.getSomething();

Constructor Injection

Now in order to make Dep1 non-static, we make it a AutoFactory:

It means: To build an instance of Dep1, execute this constructor, passing in values for all of its parameters: This pattern is called constructor injection.

And the following class which is dependent on it, will have its constructor injected to it:

The fragment contains the inject() within onCreate():

*** Troubleshooting Tip: If the Fragment doesn’t contain the inject(), it’ll throw a NullPointerException on the class that is being referenced within the fragment. In this case, it is CoolClass.

Later if you have to add a new class X that is dependent on Dep1, you’ll have to pass it as a parameter only here:

The Factory generated, takes care of the calls throughout the database, irrespective of whether the call is from the new class X or another entirely new class Y, you don’t have to worry about each call and only have to pass the dependency Y as a parameter once in the constructor of Dep1 and the generated Factory takes care of the rest:

Generated factory is as follows:

Also need to ensure that the FragmentComponent has the HomeFragment injected:

Troubleshooting Tip: If the above step doesn’t happen, then you will encounter a DaggerApplicationcomponent not found exception.

Field Injection

If you have a non-Fragment in your codebase that depends on Dep1, then use field injection instead of constructor injection:

Dep1 _dep1;

If you have an abstract class that is dependent on the Dep1, make sure you make the first concrete class as a AutoFactory.

To view or add a comment, sign in

Others also viewed

Explore content categories