Created
February 6, 2021 19:30
-
-
Save Livshitz/eabba4223bf5469d0dfb85469d86e494 to your computer and use it in GitHub Desktop.
di.libx.js example with plain JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const di = require("di.libx.js").default; | |
const { DependencyInjector } = require("di.libx.js"); | |
// Modules declaration: | |
class ModuleA { | |
options = { | |
power: 2, | |
} | |
constructor(helper) { | |
this.helper = helper; | |
} | |
calc(input) { | |
return this.helper.power(input, this.options.power); | |
} | |
} | |
class ModuleB { | |
constructor(moduleA) { | |
this.moduleA = moduleA; | |
} | |
Run(input) { | |
return this.moduleA.calc(input); | |
} | |
} | |
class HelperModule { | |
power(input, power) { | |
return Math.pow(input, power); | |
} | |
} | |
// Somewhere in main startup location the main modules are initiated and registered: | |
di.register('helper', new HelperModule()); | |
// Initiate ModuleA with it's dependencies | |
di.register('moduleA', di.initiate(ModuleA)); | |
// or alternatively manually inject the dependency and manually initiate the module: | |
/* | |
di.inject((helper: HelperModule)=>{ | |
di.register('moduleA', new ModuleA(helper)); | |
}); | |
*/ | |
// Change injected module configuration: | |
di.inject((moduleA) => { | |
moduleA.options.power = 3; | |
}); | |
// Register a local scoped container that inherits from the main container. | |
// All locally registered modules will be disposed once exited scope. | |
const subContainer = new DependencyInjector(di); | |
subContainer.register('moduleB', di.initiate(ModuleB)); | |
// Main execution point: | |
subContainer.inject((moduleB) => { | |
const result = moduleB.Run(10); | |
console.log('Result: ', result); | |
}).then(() => { | |
console.log('DONE!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment