Approach Dagger 2 with 3 lines of code

Tram Ho

In programming, we always want to find the best ways to refactor code so that it is even simpler. This article will show a simpler way to explain Dagger 2. You can think of it as a quick guide to Dagger 2.

Only 3 lines of code

To make Dagger 2 work, we will only need these 3 lines of code

Just add these lines of code to any Kotlin file in your project, and click the ▶ ️ button next to the fun main() method, and it will be executed.

Note: You will need to include the library first in the build.gradle file


The special part of Dagger 2

From the 3 lines of code above, you will see 3 unique Dagger 2 unique designations, as explained below.

@Inject constructor ()

This is the part that it shows to Dagger 2 to automatically build this object.

@Component interface

This is the part that it shows to Dagger 2 to implement the interface (in our case, the MagicBox ), the code will be generated and build all injectable dependencies. The implementation is named DaggerMagicBox .

For a detailed code, you can refer here 3 lines of Working Dagger 2 Example Code

DaggerMagicBox.create ()

As mentioned in the section above, DaggerMagicBox an auto-generated implementation of the @component interface declared. It has a create() function that initializes this implementation. From there, we can extract the dependent object easily.

From above, we see that Dagger 2 automatically creates an Info object through the DaggerMagicBox container class.

How can I automatically inject my dependency?

The code we have above doesn’t look like a Dependency Injection pattern, but instead is a Service Locator pattern, like fun main() needs to get an Info object from DaggerMagicBox . This is similar to setting it to a variable as below.

But what we want is auto-injection, like the Dagger 2 code inside the duowis:

To achieve this, we only need to do some additional work beyond the 3 lines of code above.

1. Create a target class to contain dependencies

In the above code, we need the lateinit var because that variable is not known during object class building.

2. Replace the val component with a function to inject the target object

Change the code below:

From there, it informs the components, instead of having a way to create Info in the MagicBox itself. It can inject the dependencies (such as Info ) inside the target class object (eg MainClass ) when the poke function is called.

3. Inject the dependencies inside a target class

Finally, just initialize the DaggerMagicBox in the target class, and ask it to inject the necessary dependencies (using the poke function), as in the example below.

With the above, the whole code looks like below.

In short, the advantage of Dagger 2 lies behind the automatic creation of the DaggerMagicBox object, which is the implementation of the MagixBox interface.

Hope this article will be of much help to you.

Reference source:

Share the news now

Source : Viblo