Simple Dependency Injection for node.js
npm install simple-ioc
An example of setting up the ioc
require( 'simple-ioc' )
.setLogLevel( 3 )
.register( 'settings', require( './configuration/settings' ) )
.register( 'packageInfo', require( './package.json' ) )
.register( 'amqp', require( 'amqp' ) )
.autoRegister( './lib/' )
.register( 'app', './handlers/itemQueryHandler.js' )
.start( function( packageInfo, ioc ) {
// ioc not used here but can be injected
console.log( 'Application started, version:', packageInfo.version );
} );
An example of an injected component, in this case './handlers/itemQueryHandler.js'
module.exports = function( settings, amqp ) {
...some code...
return {
...something...
};
};
Sets the level of logging and returns the ioc
0
: FATAL1
: ERROR2
: WARNING3
: INFO4
: DEBUG
Example:
ioc.setLogLevel( 1 );
Only outputs FATAL and ERROR logs.
NOTE: FATAL errors exists the application.
Sets the a log function and returns the ioc.
By default simple-ioc logs to console, but can be changed.
Simple-ioc calls the function with the following parameters:
function( level, title, message )
Registers a component and returns the ioc.
Registers a required component and returns the ioc.
Example:
ioc.registerRequired( 'module_from_other_project', require( 'module_from_other_project_in_node_modules' ) );
Automatically registers a component or a path with several components using filenames as name and returns the ioc.
Example:
ioc.autoRegister( './lib/' );
vill register all .js files under lib folder.
Resolves all registered components and optionally injects a function.
Example:
ioc.start( function( settings, packageInfo ) {
...some code that is depending on settings and packageInfo...
} );
Start can be called again if additional components are registered after start.
Injects a function. Normally only used in tests
Example:
ioc.inject( function( settings, packageInfo ) {
...some code that is depending on settings and packageInfo...
} );
Inject is intended to be used only in tests.
Note: Inject does not resolve or load registered components. The method assumes start()
was called before injection of registered components.
Gets a loaded component by name.
Example:
var settings = ioc.getLoaded( 'settings' );
getLoaded is intended to be used only in tests.
Note: getLoaded does not resolve or load registered components. The method assumes start()
was called before getLoaded of registered components.
Resets the ioc, for testing purposes.
Example:
ioc.reset();
reset is intended to be used only in tests.