3 Revitalized dependency injection
This chapter covers
- Understanding how the dependency injection mechanism works under the hood
- Learning about injection contexts
- Using the “inject” function instead of constructor-based dependency injection and the benefits of this approach
- Using the “inject” function to convert class-based guards/resolvers/interceptors to functional ones
Dependency injection, or DI, is famously the most loved and stable feature that Angular provides as a framework. DI is used extensively in every single Angular project, and it is hard to imagine a flexible and maintainable codebase without its advantages. So what changed, and importantly, why, if it was already so stable? This will be our subject of exploration in this chapter, which, funnily enough, actually revolves around one single function, “inject” (actually not even a new function!), which, almost accidentally, made a minor revolution in Angular projects all over the community.
3.1 How does dependency injection work?
Let’s start our exploration by diving into the DI mechanism to try and understand how it actually works, and how we can utilize it to build more flexible codebases. But first, let’s briefly discuss what DI is in general, and what it is not.