-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.go
124 lines (100 loc) · 2.47 KB
/
container.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package gioc
import (
"errors"
"reflect"
"sync"
)
var container map[reflect.Type]binding
var mu *sync.Mutex
func init() {
container = make(map[reflect.Type]binding)
mu = &sync.Mutex{}
}
type binding struct {
singleton bool
resolved bool
resolver interface{}
instance interface{}
}
// Singleton binds a resolver to an abstraction once
func Singleton(resolver interface{}) {
Bind(resolver, true)
}
// Bind binds a resolver to an abstraction
func Bind(resolver interface{}, singleton bool) {
mu.Lock()
defer mu.Unlock()
resolverType := reflect.TypeOf(resolver)
if resolverType.Kind() != reflect.Func {
panic("ioc resolver should be a function")
}
if resolverType.NumOut() != 2 {
panic("ioc resolver should have two return types")
}
if resolverType.Out(1) != reflect.ValueOf(new(error)).Elem().Type() {
panic("ioc resolver second return type should be error")
}
container[reflect.TypeOf(resolver).Out(0)] = binding{
singleton: singleton,
resolved: false,
resolver: resolver,
}
}
// Make loads given parameter's value from container
func Make(receiver interface{}) error {
receiverType := reflect.TypeOf(receiver)
return resolveType(receiverType, receiver)
}
func getBindingFor(t reflect.Type) (binding, bool) {
b, ok := container[t]
if !ok {
if reflect.Ptr == t.Kind() {
b, ok = container[t.Elem()]
}
}
return b, ok
}
func (b binding) resolve() (interface{}, error) {
if b.singleton && b.resolved {
return b.instance, nil
}
args, err := getArgumentsOf(b.resolver)
if err != nil {
return nil, err
}
values := reflect.ValueOf(b.resolver).Call(args)
if values[1].Interface() != nil {
return nil, values[1].Interface().(error)
}
if b.singleton && !b.resolved {
b.instance = values[0].Interface()
b.resolved = true
}
return values[0].Interface(), nil
}
func getArgumentsOf(function interface{}) ([]reflect.Value, error) {
fType := reflect.TypeOf(function)
argsCount := fType.NumIn()
args := make([]reflect.Value, argsCount)
for i := 0; i < argsCount; i++ {
abstract := fType.In(i)
var instance interface{}
if err := resolveType(abstract, &instance); err != nil {
return nil, err
}
args[i] = reflect.ValueOf(instance)
}
return args, nil
}
func resolveType(t reflect.Type, receiver interface{}) error {
b, ok := getBindingFor(t)
if !ok {
return errors.New("binding not found")
}
concrete, err := b.resolve()
if err != nil {
return err
}
reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(concrete))
return nil
}