node.js Dependency Injection
This module provides dependency injection for node.js
npm i hekdi
hekdi
popular frameworks integration:
Basic usage:
const { createModule } = require('hekdi');
class Dependency1 {
constructor() {
this.name = 'Dependency1';
}
}
class Dependency2 {
static get $inject() {
return ['LocalDependency'];
}
constructor(d1) {
this.name = 'Dependency2';
this.d1 = d1;
}
}
module.exports = createModule({
name: 'ImportedModule',
declarations: [
{ name: 'LocalDependency', strategy: 'singleton', value: Dependency1 },
{ name: 'PublicDependency', strategy: 'factory', value: Dependency2 },
{ name: 'Arr', strategy: 'value', value: [1, 2, 3] }
],
exports: ['PublicDependency', 'Arr']
});
const { createModule } = require('hekdi');
const importedModule = require('./imported.module');
class Ctrl {
static get $inject() {
return ['PublicDependency', 'Arr'];
}
constructor(publicDep, arr) {
console.log(publicDep, arr);
}
}
module.exports = createModule({
name: 'SharedModule',
declarations: [
{ name: 'Controller', strategy: 'singleton', value: Ctrl },
{ name: 'ControllerAs', strategy: 'alias', value: 'Controller' }
],
imports: [ importedModule ]
})
const { DI } = require('hekdi');
const MainModule = require('./main.module');
const di = DI.create();
di.bootstrap(MainModule);
const ctrl = di.resolve('ControllerAs');
Main concepts:
Top level API:
Top level api is DI
class that bootstraps main module and serves dependencies from it then.
const { DI } = require('hekdi');
const di = DI.create();
di.module(moduleConfig)
di.bootstrap(moduleConfig)
const dep = di.resolve('dependency')
Modularity:
DI provides modules as a structural unit of app.
declarations
array sets own dependencies of this module.exports
array tells what dependencies are available for other modulesimports
array will inject exported members from other module to this one
const { createModule } = require('hekdi');
createModule({
name: 'SomeModule',
declarations: [
{ name: 'LocalDependency', strategy: 'singleton', value: class X {} },
{ name: 'PublicDependency', strategy: 'factory', value: class Y {} },
{ name: 'Arr', strategy: 'value', value: [1, 2, 3] },
{ name: 'ZProvider', strategy: 'provider', value: () => ({ name: 'Z', strategy: 'factory', value: class Z {} })}
],
exports: ['PublicDependency', 'Arr'],
imports: [ AnotherModuleInstance ]
});
Strategies:
factory
- each time a new instance will be created.singleton
- only one instance will be created.value
- just will be returned.constant
- the same as value
but can't be reassign.alias
- used to create an alias for some dependency.provider
- function that will be called, to get dependency config.
Providers register dependencies before others do. Providers can't be exported from module.