blob: 1241552a5ecdc274ee5a402f8511726a0f705893 (
plain)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
export class Resolver {
constructor(factory) {
this.factory = factory;
}
resolveWith(container) {
if (this.isConstructor()) {
return this.resolveDependenciesUsing(container);
}
else {
return this.factory(container);
}
}
parseConstructor(func) {
let code = func.toString();
let regex = /function ([a-zA-Z]*)\((.*)\) *\{/;
return code.match(regex);
}
isConstructor() {
return this.parseConstructor(this.factory)[1] != '';
}
resolveDependenciesUsing(container) {
let parameters = this.parseConstructor(this.factory).slice(2)[0].split(',').filter(Boolean);
let dependencies = parameters.map((parameter) => container.resolve(parameter));
return new this.factory(...dependencies);
}
}
export class Registration {
constructor(key, factory) {
this.key = key;
this.factory = factory;
}
create(container) {
return new Resolver(this.factory).resolveWith(container);
}
asSingleton() {
let originalFactory = this.factory;
let item = null;
this.factory = (container) => {
if (item == null) {
item = new Resolver(originalFactory).resolveWith(container);
}
return item;
};
}
}
export default class Registry {
constructor() {
this.registrations = {};
}
register(key, factory) {
if (this.registrations[key] == undefined) {
this.registrations[key] = [];
}
let registration = new Registration(key, factory);
this.registrations[key].push(registration);
return registration;
}
resolve(key) {
try {
return this.registrations[key][0].create(this);
} catch(error) {
console.error(`ERROR: Could Not Resolve ${key}`);
console.error(error);
throw error;
}
}
resolveAll(key) {
return this.registrations[key].map(registration => registration.create(this));
}
}
|