...

/

Wiring Modules: Dependency Injection

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 ...