Simple Javascript Dependency Injection Container (DI) like Pimple, well tested browser/node - ES6 Arrow Functions compatible
NOTE : this is V2. The V2 doesn't support callback anymore and can broke compatibity with old node versions in the future. Please use the v1 if you need to use callbacks or old node version.
npm install --save simple-dijs
// NodeJs
var Di = require('simple-dijs');
// Web (just an example)
ln -s node_modules/simple-dijs/dist/di.js public/lib/di.js
// And minified : Only 4 K !
ln -s node_modules/simple-dijs/dist/di.min.js public/lib/di.min.js
<!-- Available global or ADM (requirejs), thanks to Browserify -->
<script src="lib/di.js" type="text/javascript"></script>
<!-- Exists di.min.js -->
<script src="lib/di.min.js" type="text/javascript"></script>
// Simple instanciation
var di = new Di();
// Also instanciation with services
new Di({
'database': function () { ... },
'userCollection': function (di) { ... }
});
di.set('database', function () {
return new Database();
});
di.set('userCollection', function (di) {
return new UserCollection(di.get('database'));
});
// Or multiple services
di.batchSet({ ..same than construct.. });
// So, ...
di.get('userCollection').find(1); // UserCollection instanciated now !
di.get('userCollection').find(1); // The same UserCollection instance
// If you want to factory instead of return the same object :
di.set('userCollection', di.factory(function (di) {
return new UserCollection(di.get('database'));
}));
// So, ...
di.get('userCollection').find(1); // UserCollection instanciated now !
di.get('userCollection').find(1); // Other UserCollection instance now, instanciated now !
// You can store raw values
di.set('port', 80);
di.get('port'); // 80
// Protect function you want to register raw :
di.set('math.add', di.protected(function (a, b) {
return a + b;
}));
// New feature in v2 ! You can inject your dependencies in arguments
di.set('database', function (config, logger) { // You have declared config and logger
return new Database(config.database, logger);
});
// Or with ES6 Arrow Functions
di.set('database', (config, logger) => new Database(config.database, logger) });
// You cannot use callbacks anymore. Please see version 1.x
// You can use promise (native or not)
di.set('async', function () {
return new Promise(/*Blabla*/);
});
di.get('async').then(function () {
// ...
});
// You can chain the methods calls
(new Di()).set(...).set(...);
- A complete build is configured. Always green before release
- Tests are written before code (TDD) : The what before the how
- Uses the http://semver.org/ versionning
- Please report issues and suggestions https://github.com/gallofeliz/simple-dijs/issues
- Please watch the github project if you use
- Please star the github project if you like
Kind: global class
- Di
- new Di([values])
- .batchSet(values) ⇒
Di
- .factory(func) ⇒
function
- .get(id, callback) ⇒
undefined
- .get(id) ⇒
*
- .has(id) ⇒
boolean
- .keys() ⇒
Array.<string>
- .protect(func) ⇒
function
.register()- .remove(id) ⇒
Di
- .set(id, funcOrValue) ⇒
Di
Create a new Container
Param | Type | Description |
---|---|---|
[values] | Object.<string, *> |
Values to set on construction (eqiv batchSet batchSet) |
Example
var di = new Di()
Example
var di = new Di({
id1: value1,
id2: value2
})
di.batchSet(values) ⇒ Di
Multiple set values
Kind: instance method of Di
Returns: Di
- himself
Throws:
Error
If values is not provided or not Object
Param | Type | Description |
---|---|---|
values | Object.<string, *> |
Values to set |
Example
di.batchset({
id1: value1,
id2: value2
})
Create a factory function
Kind: instance method of Di
Returns: function
- The same function
Throws:
Error
Missing or incorrect argumentError
Protected function
See: Di#set
Param | Type | Description |
---|---|---|
func | function |
The function to factory |
Example
di.set('token', di.factory(function () {
return new Token();
}))
Get a value asynchronously with callback (registered with callback)
Kind: instance method of Di
Throws:
Error
Missing or incorrect argumentError
Missing value (not registered)Error
Unexpected callback for no-callback registered valueError
Invalid callback
Param | Type | Description |
---|---|---|
id | string |
The value id |
callback | function |
The callback |
Example
di.get('database', function (err, database) {
if (err) {
// ...
}
database.find(userId);
})
Get a value synchronously
Kind: instance method of Di
Returns: *
- The value
Throws:
Error
Missing or incorrect argumentError
Missing value (not registered)Error
Missing callback for callback-registered value
Param | Type | Description |
---|---|---|
id | string |
The value id |
Example
di.get('database').find(userId)
Check that the container owns the provided id
Kind: instance method of Di
Returns: boolean
- If id is owned by the container
Param | Type | Description |
---|---|---|
id | string |
Id to check |
Example
di.has('database') || di.set('database', ...)
Get all the ids
Kind: instance method of Di
Returns: Array.<string>
- the ids
Protect a function to store as raw
Kind: instance method of Di
Returns: function
- The same function
Throws:
Error
Missing or incorrect argumentError
Factory function
See: Di#set
Param | Type | Description |
---|---|---|
func | function |
The function to factory |
Example
di.set('math.add', di.protect(function (a, b) {
return a + b;
}))
Deprecated
Kind: instance method of Di
di.remove(id) ⇒ Di
Remove a value
Kind: instance method of Di
Returns: Di
- himself
Throws:
Error
Missing or incorrect argumentError
Missing value (not registered)
Param | Type | Description |
---|---|---|
id | string |
The value id |
Example
di.remove('database')
di.set(id, funcOrValue) ⇒ Di
Set a value in the container. The registered value is by default the returned value.
In case you use a function to factory your value :
- you can use the first injected argument that is the current Di instance.
- you can register your value (for example for asynchronous) by declaring and calling the second possible argument "callback", as a normal node callback.
Kind: instance method of Di
Summary: Set a value in the container, synchronously or asynchronously
Returns: Di
- himself
Throws:
Error
if missing or incorrect argumentsError
if Id is already registered
Param | Type | Description |
---|---|---|
id | string |
The id of value |
funcOrValue | * |
The value |
Example (Set a raw value)
di.set('color', '#ff0000')
Example (Set a building function (value with be cached after first call))
di.set('database', function (di) {
return new Database(di.get('database_url'));
})
Example (Set a factory function (value will be factoryed each call))
di.set('token', di.factory(function () {
return new Token();
}))
Example (Set a building function that returns a promise)
di.set('config', function () {
return fsPromise.readFile('config.json');
})
Example (Set a building function that use callback for async)
di.set('config', function (di, callback) {
fs.readFile('config.json', callback);
})