-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinder.go
72 lines (59 loc) · 1.81 KB
/
binder.go
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
package inversify
import "sync"
// Binding holds factory, specified dependencies and resolved dependencies
type Binding struct {
once sync.Once
factory FactoryFunc
resolves NAny
dependencies NAny
}
// To binds to any object that can converted to interface{}
func (b *Binding) To(obj Any) *Binding {
b.factory = func() (Any, error) {
return obj, nil
}
return b
}
// ToFactory binds to abstract function with specified dependencies
func (b *Binding) ToFactory(factoryMethod Any, dependencies ...Any) *Binding {
return b.toFactoryMethod(wrapAbstractApplyFuncAsSlice(factoryMethod), dependencies...)
}
// ToTypedFactory binds to typed function with specified dependencies
func (b *Binding) ToTypedFactory(factoryMethod Any, dependencies ...Any) *Binding {
return b.toFactoryMethod(wrapTypedApplyFuncAsSlice(factoryMethod), dependencies...)
}
func (b *Binding) toFactoryMethod(factoryMethod func([]Any) (Any, error), dependencies ...Any) *Binding {
b.dependencies = dependencies
noDependency := []Any{}
dependenciesCount := len(dependencies)
if dependenciesCount == 0 {
b.factory = func() (Any, error) { return factoryMethod(noDependency) }
return b
}
b.factory = func() (Any, error) {
var err error
resolvedDependencies := make([]Any, dependenciesCount, dependenciesCount)
for index, dependency := range b.resolves {
resolvedDependencies[index], err = dependency.(FactoryFunc)()
if err != nil {
return nil, err
}
}
return factoryMethod(resolvedDependencies)
}
return b
}
// InSingletonScope declares dependency as singleton
func (b *Binding) InSingletonScope() {
var instance Any
var err error
originalFactory := b.factory
b.factory = func() (Any, error) {
if instance == nil {
b.once.Do(func() {
instance, err = originalFactory()
})
}
return instance, err
}
}