Dagger 2 is the most popular dependency injection framework in the Android world. The problem is that it is not that easy to master.
Here I decided to gather a number of different resources to cover everything related to learning Dagger 2, from the very basics to advanced usage in forms of text, video and code.
If you never used Dagger 2 before and want to get it up and running in your project this article contains everything you need.
Let’s check out some code. Here is a simplest Dagger 2 setup with single component.
This level is enough for a small project, for example, a test when applying for a job.
Next step would be the splitting of your component class. This level is enough to maintain clean DI in your application. Why would you want to do it? Here are 3 main reasons:
- Convert some of your global singletons into local singletons to save some memory.
- Decrease the size of your component class.
- Inject activity context.
To recap, there are two classic approaches to splitting the component class: Component Dependencies and Subcomponents. Those are two main approaches you need to become familiar with at this stage.
Let’s revisit subcomponents again, here is the comparison:
And a code sample:
Some thoughts on how to split components:
Now let’s check some code.
Dependent components example:
Here you’ll learn features to make your DI code cleaner.
Following article covers some cool features available in Dagger 2.
In the following part we are introducing more way of scoping, they are Android specific and more advanced.
- First one is called Activity Multibinding.
- Second one is Android Injector.
It’s time to revisit everything that we learned above, check out the video covering most of the information.
And this awesome project showcasing and comparing all approaches.
A huge advantage of using DI is increased code testability. Here we look at best practices of testing with Dagger 2.
Now you should be very comfortable with using Dagger 2, but it is not the only framework. Check out other DI frameworks in this section. I’ll cover 3 in different formats: text, video and code, so you can pick whichever you prefer.
Kodein Github repo: