Lightweight asynchronous promise-based dependency injector (60 lines of code).
npm install q-injector
var Injector =app = ; // create application based on the Injector// register dependency `service1` within the injectorapp;// register a factory method of dependency `service2`app;// register an asynchronous factory method for `service3`app;// initiates dependency initialization and injects initialized dependenciesapp;// another method to inject a dependencyapp;
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
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
If it's not still clear how q-injector works, take a look at provided testsuite. There are all possible use cases.