1 The basics of Dependency Injection: What, why, and how


In this chapter

  • Dispelling common myths about Dependency Injection
  • Understanding the purpose of Dependency Injection
  • Evaluating the benefits of Dependency Injection
  • Knowing when to apply Dependency Injection

You may have heard that making a sauce béarnaise is difficult. Even among people who regularly cook, many have never attempted to make one. This is a shame, because the sauce is delicious. (It’s traditionally paired with steak, but it’s also an excellent accompaniment to white asparagus, poached eggs, and other dishes.) Some resort to substitutes like ready-made sauces or instant mixes, but these aren’t nearly as satisfying as the real thing.

A sauce béarnaise is an emulsified sauce made from egg yolk and butter, that’s flavored with tarragon, chervil, shallots, and vinegar. It contains no water. The biggest challenge to making it is that its preparation can fail. The sauce can curdle or separate, and, if either happens, you can’t resurrect it. It takes about 45 minutes to prepare, so a failed attempt means that you may not have time for a second try. On the other hand, any chef can prepare a sauce béarnaise. It’s part of their training and, as they’ll tell you, it’s not difficult.

1.1 Writing maintainable code

1.1.1 Common myths about DI

1.1.2 Understanding the purpose of DI

1.2 A simple example: Hello DI!

1.2.1 Hello DI! code

1.2.2 Benefits of DI

1.3 What to inject and what not to inject

1.3.1 Stable Dependencies

1.3.2 Volatile Dependencies

1.4 DI scope

1.4.1 Object Composition

1.4.2 Object Lifetime

1.4.3 Interception

1.4.4 DI in three dimensions

1.5 Conclusion