-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathContainer.js
57 lines (46 loc) · 1.53 KB
/
Container.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Container {
constructor() {
this._services = new Map()
this._singletons = new Map()
}
register(name, definition, dependencies) {
this._services.set(name, {definition: definition, dependencies: dependencies})
}
singleton(name, definition, dependencies) {
this._services.set(name, {definition: definition, dependencies: dependencies, singleton:true})
}
get(name) {
const c = this._services.get(name)
if(this._isClass(c.definition)) {
if(c.singleton) {
const singletonInstance = this._singletons.get(name)
if(singletonInstance) {
return singletonInstance
} else {
const newSingletonInstance = this._createInstance(c)
this._singletons.set(name, newSingletonInstance)
return newSingletonInstance
}
}
return this._createInstance(c)
} else {
return c.definition
}
}
_getResolvedDependencies(service) {
let classDependencies = []
if(service.dependencies) {
classDependencies = service.dependencies.map((dep) => {
return this.get(dep)
})
}
return classDependencies
}
_createInstance(service) {
return new service.definition(...this._getResolvedDependencies(service))
}
_isClass(definition) {
return typeof definition === 'function'
}
}
export default Container