Simple IoC Container
Installation:
npm i simple-ioc-container --save
It's really simple DI container with two main methods "register()" and "get()" to manipulate dependencies. This package has one dependence and suits for a front and back side code. Injection is implemented really simply as well (see examples).
API
Properties:
- proxy - Proxy of an Injector instance for simple access to dependencies via properties.
Methods:
register(...dependencies)
Registers dependence(ies) in a container with specified params.
- dependencies {...Object} dependencies - Params of a dependence. Description:
- key[required]: {string} dependence key;
- type[required]: {enum} ["value", "factory", "service"];
- value[required]: {*} Any data. Module will be connected if a type is "factory" or "service" and a value is set like a string;
- force[optional]: {bool} registers forcefully if true, otherwise doesn't. Default false;
- onRegister[optional]: {callback} Invokes if a dependence is successfully registered.
Returns an Injector instance(this).
get(key, [...args])
Returns a dependence by a key.
- key {*} Key to get a dependence for.
- args {...*} Arguments to bind to a constructor..
Returns a dependence.
getConstructor(key)
Returns a dependence constructor.
- key {*} Key to get a dependence for.
Returns a dependence constructor.
Note: a dependence has to have a constructor.
Examples
// di.js ; Injector;
// dependencies.js ;;; di ; // or if are not reciprocal dependenciesdi
// models/User.js moduleexports = { const userService config db = this_di; thisuserService = userService; // id => 007 in this example // userService, config and db are registered dependencies from di }
// ...some.js ; const serviceA = di;const admin = di;const serviceB = diproxyuserService; di; const serviceC = diproxyuserService; /* admin instanceof User => true admin.userService == serviceA => true serviceA == serviceB => true serviceA == serviceC => false*/
todo
- tests
- improving the docs