Dagger 2 - The Return of Dependency Injection
By Marika Engström | October 26, 2018
When I first stumbled over Inversion of Control (IoC) design principle more than ten years ago, I was all sold on it. Especially the dependency injection (DI) design pattern with constructor injection. This pattern forced developers into a design that made isolated (unit) testing really easy.
At that time one of the most used frameworks for DI was the Spring framework. If you have been using Spring you probably know that the validation of the dependency graph is made runtime. The big downside with this is that mistakes in configuration are not discovered until running the code.
Another downside at the time was the configuration format – Spring was using XML. This meant that configuration of all the objects used for injection required almost as many rows as writing the code. Fortunately this problem was addressed when annotations were enabled and the configuration moved closer to code.
The downsides, together with the fact that companies started moving towards microservices, made me move away from DI frameworks.
This was until I discovered Dagger 2 a while ago.
Dagger 2 addresses both of the problems mentioned earlier. All the configuration is made using annotations together with a couple of helper classes (modules and components). The validation of the dependency injection graph is made in compile time. In addition, if you are familiar with the builder and factory design patterns, the generated code is rather easy to follow and debug.
The learning curve for Dagger 2 is quite steep. However considering the upsides when configuring your application, for example for different kinds of testing, it is well worth it.