Dagger: Implement the full stack with this dependency injector for Java & Android
No need for a knife fight! Today, we’re taking a look at Dagger, the extra-fast dependency injector from Google. With Dagger, developers can focus on the interesting classes without needing to create boilerplate code.
It’s been a while since we last checked in on Dagger, the open source dependency injector from Google. This compile time dependency injection framework works for both Java and Android. Dagger improves the developer’s experience with traceability, clarity, and improved performance.
Dagger unifies user-defined types with generated types through limited, well-defined entry points. The generated code looks like hand-written dependency injector code, making less work for the developers.
Dagger 2 takes a compile-time evolution approach to dependency injection. How? By getting rid of all reflection and utilizing user-specified @Component interfaces over the traditional ObjectGraph/Injector.
This framework makes things easier for developers, by generating simple Java at compile for the entire stack. Instead of having to write the boilerplate dependency injections yourself, let Dagger’s automation take care of it. Just declare the dependencies, specify exactly how you want them satisfied, and ship ‘em.
Classes are easy to test with the Dagger framework. You don’t need a bunch of custom work done just to swap out one injection for another.
Besides, dependency injection can do more than just testing code. Developers can create reusable, interchangeable modules across all their apps.
Most importantly, Dagger implements the full stack with generated code. It also validates all the framework/configuration preconditions at compile time.
Dagger 2 improves on the original by making debugging easier: it has an entirely concrete call stack for provision and creation. It is fully traceable and the performance has improved significantly. However, there are some drawbacks. It is less flexible and dynamic than the original. Also, there is no direct migration from Guice, where it originated.
Interested in trying out this fast dependency injector for yourself? Dagger is available here. Fair warning: it is currently in active deployment, so there are regular pushes to GitHub from Google, Square, and other organizations. More details can be found in the user’s guide here or from this presentation from Gregory Kick on “the least creative dependency framework yet”.