-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiContainer.js
43 lines (35 loc) · 1005 Bytes
/
diContainer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
* A DI Container.
* */
"use strict";
const fnArgs = require('parse-fn-args');
module.exports = () => {
const dependencies = {};
const factories = {};
const diContainer = {};
diContainer.factory = (name, factory) => {
factories[name] = factory;
};
diContainer.register = (name, dep) => {
dependencies[name] = dep;
};
diContainer.get = (name) => {
if (!dependencies[name]) {
const factory = factories[name];
dependencies[name] = factory &&
diContainer.inject(factory);
if (!dependencies[name]) {
throw new Error('Cannot find module: ' + name);
}
}
return dependencies[name];
};
diContainer.inject = (factory) => {
const args = fnArgs(factory)
.map(function (dependency) {
return diContainer.get(dependency);
});
return factory.apply(null, args);
};
return diContainer;
};