Lightweight asynchronous promise-based dependency injector
Lightweight asynchronous promise-based dependency injector (60 lines of code).
npm install q-injector
var Injector = require'q-injector'app = ; // create application based on the Injector// register dependency `service1` within the injectorappinstance'service1'/* ... */// ...;// register a factory method of dependency `service2`appinstance'service2' // inject `service3` into the factory methodreturn /* ... */ ;;// register an asynchronous factory method for `service3`appinstance'service3'// ...return thenable; // returns promise, that will be resolved// during injection of `service3` into `service2`;// initiates dependency initialization and injects initialized dependenciesappinvoke// at this point all services are resolved,// `service3` is injected into `service2` factory methodservice1method1;// ...;// another method to inject a dependencyappget'service1'thenservice1method1;// ...;
Dependency is an object used by other objects. A dependency have a name, used by other objects to refer to the dependency.
Dependency injection is a process of dependency resolution. Objects get links to their dependencies declared by names.
An Injector instance has a single namespace for dependencies. Dependency named
service1 will be always the same within the Injector instance.
One dependency can depend on other, others can depend on another, etc. By
injector.factory() you define dependency graph which will be
resolved during injection, when you call
Register an object
obj as dependency named
Register a factory method
factory which will be used to construct a
name. Factory method
factory won't be invoked until
name is requested to be injected into another object.
will be invoked using
injector.invoke() method, which means that factory
method may have dependencies as well.
Factory method is called only once and its return value is cached in the Injector instance.
factory may return a plain object or a promise, which will be resolved before
being injected into another object.
locals is an override of dependencies injected into the
appfactory'service1'service2 == 's2' // true// service3 is previously registered dependencyservice2: 's2';
Resolve previously registered dependency by
name and return a promise.
fn function declaration argument names, resolve previously registered
dependencies by their names and invoke
fn with the dependecies.
Returns a promise which will be resolved to a return value of
locals is an override of dependencies injected into
appinvokeservice2 == 's2' // true// service1 is previously registered dependencyreturn 'hello';service2: 's2'thenret == 'hello' // true;
If it's not still clear how q-injector works, take a look at provided testsuite. There are all possible use cases.