-
Notifications
You must be signed in to change notification settings - Fork 55
/
di.go
71 lines (63 loc) · 1.36 KB
/
di.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
package zdi
import (
"reflect"
)
type (
Injector interface {
Invoker
TypeMapper
Set(reflect.Type, reflect.Value)
Get(reflect.Type) (reflect.Value, bool)
SetParent(Injector)
}
Invoker interface {
Apply(Pointer) error
Resolve(...Pointer) error
Invoke(interface{}) ([]reflect.Value, error)
}
TypeMapper interface {
Map(interface{}, ...Option) reflect.Type
Maps(...interface{}) []reflect.Type
Provide(interface{}, ...Option) []reflect.Type
}
)
type (
Pointer interface{}
Option func(*mapOption)
mapOption struct {
key reflect.Type
}
injector struct {
values map[reflect.Type]reflect.Value
providers map[reflect.Type]reflect.Value
parent Injector
}
)
func New(parent ...Injector) Injector {
inj := &injector{
values: make(map[reflect.Type]reflect.Value),
providers: make(map[reflect.Type]reflect.Value),
}
if len(parent) > 0 {
inj.parent = parent[0]
}
return inj
}
func (inj *injector) SetParent(parent Injector) {
inj.parent = parent
}
func WithInterface(ifacePtr Pointer) Option {
return func(opt *mapOption) {
opt.key = ifeOf(ifacePtr)
}
}
func ifeOf(value interface{}) reflect.Type {
t := reflect.TypeOf(value)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Interface {
panic("called inject.key with a value that is not a pointer to an interface. (*MyInterface)(nil)")
}
return t
}