-
Notifications
You must be signed in to change notification settings - Fork 1
/
container.go
110 lines (94 loc) · 2.08 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
package xdi
import (
"errors"
"fmt"
"reflect"
"sync"
)
var DefaultContainer *Container
func init() {
DefaultContainer = New()
}
func New() *Container {
return &Container{}
}
func Provide(objects ...*Object) error {
return DefaultContainer.Provide(objects...)
}
func Populate(name string, ptr interface{}) error {
return DefaultContainer.Populate(name, ptr)
}
type Container struct {
Objects []*Object
tidyObjects sync.Map
instances sync.Map
}
func (t *Container) Provide(objects ...*Object) error {
for _, o := range objects {
if _, ok := t.tidyObjects.Load(o.Name); ok {
return fmt.Errorf("xdi: object '%s' existing", o.Name)
}
t.tidyObjects.Store(o.Name, o)
}
return nil
}
func (t *Container) Object(name string) (*Object, error) {
v, ok := t.tidyObjects.Load(name)
if !ok {
return nil, fmt.Errorf("xdi: object '%s' not found", name)
}
obj := v.(*Object)
return obj, nil
}
func (t *Container) Populate(name string, ptr interface{}) (err error) {
defer func() {
if e := recover(); e != nil {
err = errors.New("xdi: " + fmt.Sprint(e))
}
}()
obj, err := t.Object(name)
if err != nil {
return err
}
if reflect.ValueOf(ptr).Kind() != reflect.Ptr {
return errors.New("xdi: argument can only be pointer type")
}
ptrCopy := func(ptr, newValue interface{}) {
v := reflect.ValueOf(ptr)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
v.Set(reflect.ValueOf(newValue))
}
if !obj.NewEverytime {
refresher := &obj.refresher
if p, ok := t.instances.Load(name); ok && !refresher.status() {
ptrCopy(ptr, p)
return nil
}
// 处理并发穿透
// 之前是采用 LoadOrStore 重复创建但只保存一个
// 现在采用 Mutex 直接锁死只创建一次
obj.mutex.Lock()
defer obj.mutex.Unlock()
if p, ok := t.instances.Load(name); ok && !refresher.status() {
ptrCopy(ptr, p)
return nil
}
v, err := obj.New()
if err != nil {
return err
}
t.instances.Store(name, v)
refresher.off()
ptrCopy(ptr, v)
return nil
} else {
v, err := obj.New()
if err != nil {
return err
}
ptrCopy(ptr, v)
return nil
}
}