Wiring Modules: Dependency Injection
Learn how to wire dependencies using the Dependency Injection pattern.
We'll cover the following
Dependency injection
The Node.js module system and the Singleton pattern can serve as great tools for organizing and wiring the components of an application together. However, these don’t always guarantee success. If, on the one hand, they’re simple to use and very practical, then on the other, they might introduce a tighter coupling between components.
In the previous example, we can see that the blog.js
module is tightly coupled with the db.js
module. In fact, our blog.js
module can’t work without the database.js
module by design, nor can it use a different database module if necessary. We can easily fix this tight coupling between the two modules by leveraging the Dependency Injection pattern.
Dependency Injection (DI) is a very simple pattern in which the dependencies of a component are provided as input by an external entity, often referred to as the injector.
The injector initializes the different components and ties their dependencies together. It can be a simple initialization script or a more sophisticated global container that maps all the dependencies and centralizes the wiring of all the modules of the system. The main advantage of this approach is improved decoupling, especially for modules depending on stateful instances (for example, a database connection). Using DI, each dependency, instead of being hardcoded into the module, is received from the outside. This means that the dependent module can be configured to use any compatible dependency, and therefore the module itself can be reused in different contexts with minimal effort.
The following illustration shows this idea:
Get hands-on with 1400+ tech skills courses.