ext-di
v1.0.11
Published
EXT - Depedency Injector
Downloads
6
Maintainers
Readme
EXT DI (EXT Dependency Injector)
Features
- simple dependency injection helper module
- let's you write unit-testable code
- simple access to your dependency - all dependencies can be accessed via the injector: createdClassInstanceByInjector.ext.get(dependencyModule)
Usage
Firstly, install it:
npm install ext-di --save
Use it like this
const Injector = require('ext-di');
let injector = new Injector({ 'redis' : { module : 'ioredis', className : 'Redis' }});
API
constructor(config)
config.ALIAS_NAME
The alias name for the class/moduleconfig.ALIAS_NAME.module
This value will be used for 'require'config.ALIAS_NAME.className
The actual class name ( leave empty if not used )config.ALIAS_NAME.params
The list of params for this instance of the class ( leave empty if not used )config.ALIAS_NAME.instantiate
Should the injector create a new instance of the 'class' ( leave empty if not used )
|Options|Effect|
|:---|---:|
|{"alias": "fs"}
|This will directly use the given module|
|{"alias": {"module": 'm'}}
|require('m')|
|{"alias": {"module": "m", "instantiate": true}}
|new require('m')()|
|{"alias": {"module": 'm', "className": 'C'}}
|require('m').C|
|{"alias": {"module": "m", "className": 'C', "instantiate": true}}
|new require('m').C()|
get(aliasName)
aliasName
string The alias name for the class. It will be instantiated using the configured params
/** complex.js **/
class Complex {
async getNr() {
let nativeService = await this.getService('native');
return nativeService.nr;
}
}
/** native.js **/
module.exports = {
nr: 123456
};
/** index.js **/
let injector = new Injector({
'complex': {module: 'complex.js', className: 'Complex', instantiate: true},
'native': {module: 'native.js'}
});
let complex = await injector.get('complex');
complex.getNr();