-
Notifications
You must be signed in to change notification settings - Fork 0
/
inject.go
210 lines (179 loc) · 5.29 KB
/
inject.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package do
import (
"fmt"
"log"
"reflect"
"unsafe"
)
// Ioc Inversion of Control, dependency inject
type Ioc struct {
enableUnexportedFieldSetValue bool // set value to unexported field
print bool
providerMap map[reflect.Type]typeInfo
cache map[reflect.Type]reflect.Value
}
type IocOption struct {
EnableUnexportedFieldSetValue bool // set value to unexported field
Print bool // print inject procedure
}
type typeInfo struct {
depType []reflect.Type
provider reflect.Value
}
func NewIoc(
opt *IocOption,
) *Ioc {
if opt == nil {
opt = &IocOption{}
}
return &Ioc{
enableUnexportedFieldSetValue: opt.EnableUnexportedFieldSetValue,
print: opt.Print,
providerMap: make(map[reflect.Type]typeInfo),
cache: make(map[reflect.Type]reflect.Value),
}
}
// RegisterProvider register provider,like `func New(fielda TypeA, fieldb TypeB) (T)`
func (ioc *Ioc) RegisterProvider(v any) (err error) {
refValue := reflect.ValueOf(v)
refType := refValue.Type()
if refType.Kind() != reflect.Func {
return fmt.Errorf("please input func")
}
// 分析函数的参数和返回值
ti := typeInfo{
depType: make([]reflect.Type, 0, refType.NumIn()),
provider: refValue,
}
for i := 0; i < refType.NumIn(); i++ {
in := refType.In(i)
ti.depType = append(ti.depType, in)
}
// 返回:instance
min := 1
if refType.NumOut() == 0 {
return fmt.Errorf("can't find result in func")
}
if refType.NumOut() < min {
return fmt.Errorf("too little result in func, min is %d", min)
}
for i := 0; i < refType.NumOut(); i++ {
out := refType.Out(i)
ioc.providerMap[out] = ti
}
return
}
// Inject init v with providers. v is a struct pointer.
//
// If provider need parameters, it will lookup a right value by it's type.
func (ioc *Ioc) Inject(v any) (err error) {
refValue := reflect.ValueOf(v)
refType := refValue.Type()
if refType.Kind() != reflect.Ptr {
return fmt.Errorf("v is not a pointer")
}
eleValue := refValue.Elem()
eleType := eleValue.Type()
if eleType.Kind() != reflect.Struct {
return fmt.Errorf("v is not a struct")
}
ioc.levelPrint(0, "will inject object of type(%s)\n", eleType.Name())
// 遍历field
for i := 0; i < eleValue.NumField(); i++ {
sf := eleType.Field(i)
field := eleValue.Field(i)
fieldType := field.Type()
var level = 1
ioc.levelPrint(level, "will set field %s(%s)\n", sf.Name, fieldType.Name())
// 根据类型查找值
var value reflect.Value
value, err = ioc.find(fieldType, level+1)
if err != nil {
return
}
// 给字段赋值
if ioc.enableUnexportedFieldSetValue {
rf := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem()
rf.Set(value)
} else {
field.Set(value)
}
ioc.levelPrint(level, "finish set field %s(%s)\n", sf.Name, fieldType.Name())
}
ioc.levelPrint(0, "finish inject object of type(%s)\n", eleType.Name())
return
}
func (ioc *Ioc) levelPrint(l int, format string, args ...any) {
if ioc.print {
prefix := "[inject] "
level := ""
for i := 0; i < l; i++ {
level += " "
}
log.Printf(prefix+level+format, args...)
}
}
var (
emptyStruct = reflect.TypeOf((*struct{})(nil))
emptyStructValue = reflect.New(emptyStruct.Elem()).Elem()
emptyStructPtrValue = reflect.New(emptyStruct).Elem()
errorType = reflect.TypeOf((*error)(nil)).Elem()
)
func (ioc *Ioc) find(typ reflect.Type, level int) (r reflect.Value, err error) {
ioc.levelPrint(level, "will get field type %s's value\n", typ.Name())
value, ok := ioc.cache[typ]
if ok {
ioc.levelPrint(level, "finish get field type %s's value from cache\n", typ.Name())
return value, nil
}
// 在provider里寻找初始化函数
provider, ok := ioc.providerMap[typ]
if !ok {
// 检查类型是否是struct{}
if typ.ConvertibleTo(emptyStruct.Elem()) {
ioc.levelPrint(level, "finish get field type %s's value from empty struct\n", typ.Name())
return emptyStructValue, nil
}
if typ.ConvertibleTo(emptyStruct) {
ioc.levelPrint(level, "finish get field type %s's value from empty struct pointer\n", typ.Name())
return emptyStructPtrValue, nil
}
return r, fmt.Errorf("can't find provider of %+v", typ)
}
// 调用
in := make([]reflect.Value, 0, len(provider.depType))
for _, dep := range provider.depType {
// 在已有provider里找指定类型
var value reflect.Value
if value, ok = ioc.cache[dep]; !ok {
value, err = ioc.find(dep, level+1)
if err != nil {
return r, err
}
ioc.cache[dep] = value
}
in = append(in, value)
}
newValues := provider.provider.Call(in)
if len(newValues) == 0 {
return r, fmt.Errorf("can't get new value by provider")
}
// 返回值里,第一个必须是实例,最后一个必须是error,中间的忽略
newValue := newValues[0]
ioc.cache[typ] = newValue
if len(newValues) > 1 {
lastValue := newValues[len(newValues)-1]
last := lastValue.Interface()
if lastValue.Type().Implements(errorType) {
if v, ok := last.(error); ok {
if v != nil {
return r, fmt.Errorf("call failed, err is %+v", v)
}
}
} else {
return r, fmt.Errorf("last return value is not error, is %+v", last)
}
}
ioc.levelPrint(level, "finish get field type %s's value from provider `%s`\n", typ.Name(), provider.provider.Type().String())
return newValue, nil
}