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.
The Dependency Inversion principle said that:
We can implement Dependency Injection in Node.js by 2 ways:
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
).
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