Chapter 16. Dependency injection
This chapter covers
Dependency injection (DI) is a technique that allows you to describe dependencies between items and inject relevant objects into your code (rather than having to code their creation yourself).
Why is this useful? It makes your upgrade path simpler, and your ability to support different devices is instantly accessible. Need to test with mock-ups? Simple, swap your functional implementation with a mock-up. Most of the time, you can do this in DI with a one-line change of code.
DI also allows you to remove a bunch of boilerplate code used in object creation, as hinted at in figure 16.1. But be careful with DI, because the removal of the boilerplate code makes it possible to lose yourself and others in dependency graphs—the result being that no one is quite sure what is created where, which leads to a maintenance issue. Like any technique, you must use it in the right place, use it carefully, and use it well.
Figure 16.1. A schematic of dependency injection in action. Here “Thing” isn’t created in our code; rather, an implementation is created and injected into our code by the DI framework in use based on a set of binding definitions.
