Dagger Demystified | Dagger Is No Longer Difficult

Puneet Grover
6 min readJan 22, 2021

Welcome to one of the most interesting and difficult topic to understand in Android Development, the Dependency Injection framework, Dagger

But Don’t worry I will make it More Simpler and Easy to Understand! 😃

Only requirement is I need your few minutes + Patience and then you will be able to use Dagger2 as a Gem, Yes Believe me !

Let’s Start!

What is the Meaning of Dependencies?

Objects used by one object are called dependencies of the object. So Don’t get confused by gradle dependency here

Let’s discuss it in more detail with an example:-

class Car {
private val engineInstance : Engine
init {
engineInstance = Engine()
startCar()
}
private fun startCar(){
engineInstance.startEngine()
}
}
  • Here in a Car class we have instance variable of type Engine. In the init{} block Car constructs a new Engine object and assigns that to engine Instance variable and later it calls to startCar function.
  • We can see Car object uses that engine instance variable to call the start function of newly created engine object

Hence in this example you can see Car class Depends on Engine class. Car class can not work without support of engine class

So we can consider engine class as a dependency for the Car class

This is the Simple example of about Dependencies, In larger projects we may use Third party Dependencies like Retrofit, Room etc

Why Dependency Injection?

If Dependencies are tightly coupled it becomes harder to do testing, bug fixing and expanding of the code

What is Tightly coupled dependency:-

If a class needs some other class / or if a class is dependent on some other object
and if that object is constructed / created in that same class that means It is coupled Tightly

And this is not a good approach for a Good Software Design

To have loosly coupled dependencies There is a need of Dependency Injection

Got the Point? No worries I will explain it in more detail

In Above example we constructed Engine class inside the Car class like this:-

init {
engineInstance = Engine()
startCar()
}

That’s not the correct approach. The Car class should get the engine dependency from outside

In other words, we should write code to construct Engine object, keep it somewhere else and inject it to the car class through an interface when needed. (Do Remember this line, I will explain it in more details later)

Name of this process is called Dependency Injection

What Is Dependency Injection

The process of Constructing required dependencies (object/entities/instances) outside of the dependent object and providing
them to the dependent object when needed is called Dependency Injection

Now if we will try to do it manually we will have to deal with Complex code logics and also it will take lot of time & effort

This is where Dependency Injection frameworks come to help us like Dagger 2 which is most successful and popular framework

Dagger makes our life easier by generating all the code for us considering the instructions given by us using a set of annotations

Lots of theory? I don’t blame you But To Make it Very clear We need to study little More and I know it will be worth your time!

There’re three ways you can do dependency injection

1. Construction Injection — Where dependencies are provided by Constructors
2. Method Injection — Where dependencies are provided by functions
3. Field Injection — Where dependencies are provided By Declaring public fields

In android development It’s recommended to use Constructor Injection as much as possible, Hence Let’s study about it with Dagger2

Constructor Injection

Let’s say we have a class Smartphone like this which further requires other classes Instance / dependencies like Battery, MemoryCard etc.

Here in LearnActivity we had code like this:-

Our first step is we need to get them to the Main Activity from an outside source instead of constructing them here, Let’s comment these above code lines

Please be noted On Some other articles you will see Dagger in different way But Here I am using much Simpler & Easier way to make you understand Dagger 2 and that too from Scratch

STEPS TO IMPLEMENT DAGGER 2:-

  1. We want Dagger to construct a SmartPhone and send it to Main Activity
  2. Now first of all Dagger has to construct all classes instance which SmartPhone class needs like Battery and Memory card instance. After that with these all Dagger can construct a SmartPhone Instance.
  3. First of All use @Inject annotation:- Whichever dependencies are required must be annotated with Inject annotation, It tells dagger that these dependencies / objects are to be injected from outside
  4. Now considering the instructions provided by us Dagger can generate code to construct dependencies represented by this dependency graph.
  5. To use dagger 2 generated code for dependency injection we also need an interface annotated with @Component.

In this interface, we will define the function to return the instance of classes we need. It’s something that will help dagger to create instances of classes and also get their dependencies

@Component
interface SmartPhoneComponent {
fun getSmartphone() : SmartPhone
}

Now have a look into the most important details :-

  1. Function name can be anything and Return type of function will be the dependency / object required. Dagger will only consider this return type
  2. If you see generated folder you will see that Dagger will create factory classes for all dependencies (i.e MemoryCardFactory, BatteryFactory etc)
  3. For your component interface Dagger will create a Class which implements that Interface component and it always includes the word Dagger in front of interface name

For SmartPhoneComponent it should be — DaggerSmartPhoneComponent

Here to get the dependency we defined a getter function and Dagger
has implemented that here

So Our Updated SmartPhone class will be:-

and our Updated LearnActivity will be:-

In Nutshell :- First annotate required Objects (Battery, MemoryCard) with Inject and then use Component interface where these dependencies are needed, Create Getter function to get Smartphone Object in Component. Use that Component Wherever Smartphone object is required i.e MainActivity

Here you can call either create() or builder() methods. These both functions creates a new object of this Dagger Component.

Now If you’re not Tired 😜 Then Let’s understand One Important thing of Dagger2 which is Modules

Don’t worry Rest things I will not cover in this, Part2 will be created for that So Hang on!

MODULES

Till now we have learned how to implement the @Inject on constructors but what if we want an object of a class we don’t own like Retrofit, Room, Context etc or an interface that doesn’t have a constructor in those cases we use @Module.

I will not go in detail about how to implement Retrofit or others classes but I will share the code below so you can understand what is happening.

Let’s Say class MemoryCard is not our Own Class hence We can’t use Inject annotation / We can’t modify that class. In that Scenario we will have simple Memory card class without Inject annotation

  1. Now we will have to create a Module class for Memory card i.e MemoryCardModule and annotate it with @Module
  2. Create a method to provide Memory card instance from that module and annotate this method with @Provides (This annotation tells the dagger how to provide classes that your project doesn’t own or it tells Dagger how to create instances of the type that this function returns).

MemoryCardModule will be like this:-

And Our next step is to go to the SmartPhoneComponent interface and add this Module:-

And It’s Done! Wohoooooo, See How Easy It Was! 😆

That’s how we Implement Dependency Injection using Dagger 2. We didn’t construct any dependency inside Main Activity Instead we constructed them outside and Injected them to the MainActivity with the support of Dagger2.

Remember to use @inject annotation for all the constructors of the dependencies and Remember to use Component interface annotated with component annotation to tell Dagger to construct those dependencies

I hope you got a good idea of Dagger2. There are many other things to discuss like Scope, Singleton etc. We will discuss them in Next section.

Please share this with your Fellow Developers, SHARING IS CARING 🙏

And Yes Do not skimp on CLAPS 👏 Claps Becomes a Motivation and Its Free Too 😛

Let’s become friends on Linkedin, Twitter

Follow on Medium for more updates

Happy Coding! 😍

--

--

Puneet Grover

Android Team Lead (Senior Consultant) @Deloitte USI | Google Certified Android Dev | Java | Kotlin | Blogger | Sometimes Youtuber