How to implement Dependency Injection in Node.js with Example

nodejs-dependency-injection-example-feature-image

Dependency Injection is one form of Inversion of Control technique that supports the Dependency Inversion principle (the last one of SOLID Principles – decoupling software modules). In this tutorial, we’re gonna look at way to implement Dependency Injection pattern in Node.js.

Dependency Injection Overview

What is the problem with tightly coupled modules?
We may end up hardwiring multiple modules. It’s difficult to change a module later, so we may need to refactor a lot of code.
=> How we can avoid writing highly cohesive and tighly coupled modules?

The Dependency Inversion principle said that:

High-level modules should not depend on low-level modules.

So, how we understand this sentence:
– Modules don’t connect to each other directly, but using interfaces/references to the modules. High-level module will use low-level module via that interface/reference. We call low-level module “dependency”.
– Dependency is instantiated before being passed (or injected) to other modules as parameters.

We can implement Dependency Injection in Node.js by 2 ways:
Constructor Injection: Dependency is injected to a class via constructor method of the class. This is the common way.
Setter Injection: Dependency is injected to a class via setter method of the class.

For example, we use config() method as the setter method to inject logger to AnyClass:

Then, if we want to use a logger, we initiate it before injecting:

Now we can use AnyThing without caring about logger details. This provides us a loose-coupling, reusable modules with different dependencies (logger-console or logger-file).

Implement Dependency Injection in Node.js

Inject Dependency

We create a Bank class that has config() method (setter method) with property called logger, logger is like an interface to plug-in any logger module.
Bank.js

Anytime we want to generate a log, just use logger.write() function. Two implementations of the logger will be created below.

Implement dependencies

Now we create 2 logger module: console and file:

Create logger-console module

logger-console/index.js

Create logger-file module

logger-file/index.js

Create Client to run

First, we initiate logger object, we can choose which logger module in need.
Then we use config() method to inject that dependency.

app.js

You can see that we can change the logger module to use flexibly.

Check result

Run command: node app.js. Here is the result (in console/text file):



By grokonez | April 8, 2019.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*