https://grokonez.com/node-js/implement-dependency-injection-node-js-example

How to implement Dependency Injection in Node.js with Example

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:

class AnyClass {

    config({ 
        logger 
    }) {
        this.logger = logger;
    }

    doSomething(amount) {
        this.logger.write(...);
        // ...
    }
    // ...
}

module.exports = new AnyClass();

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

const AnyThing = require('./AnyClass');
// const logger = require('./logger-console');
const logger = require('./logger-file');
AnyThing.config({
    logger
});

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

https://grokonez.com/node-js/implement-dependency-injection-node-js-example

How to implement Dependency Injection in Node.js with Example

#nodejs #dependency #injection

How to implement Dependency Injection in Node.js with Example » grokonez
1.70 GEEK