-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer.go
More file actions
62 lines (56 loc) · 1.51 KB
/
container.go
File metadata and controls
62 lines (56 loc) · 1.51 KB
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
package gs
import (
"reflect"
)
const initMethodName = "GoService"
// Container struct
type Container struct {
services map[interface{}]interface{}
}
// Get returns existing or creates new instance of specified type
func (c *Container) Get(i interface{}) interface{} {
service := c.services[reflect.TypeOf(i)]
if service == nil {
service = c.Create(i)
c.services[reflect.TypeOf(i)] = service
}
return service
}
// Set value of instance of specified type
func (c *Container) Set(i interface{}, v interface{}) {
c.services[reflect.TypeOf(i)] = v
}
// Create creates new instance of specified type
func (c *Container) Create(i interface{}) interface{} {
instanceType := reflect.TypeOf(i).Elem()
svc := reflect.New(instanceType)
for i := 0; i < instanceType.NumField(); i++ {
field := instanceType.Field(i)
fieldType := field.Type
if fieldType.Kind() != reflect.Ptr {
continue
}
fieldTypeElem := fieldType.Elem()
if fieldTypeElem.Kind() != reflect.Struct {
continue
}
f := svc.Elem().Field(i)
if !f.CanSet() {
continue
}
val := c.Get(reflect.Zero(fieldType).Interface())
f.Set(reflect.ValueOf(val))
}
method, ok := svc.Type().MethodByName(initMethodName)
if ok {
argumentsCount := method.Type.NumIn()
arguments := make([]reflect.Value, argumentsCount-1)
for i := 1; i < argumentsCount; i++ {
s := c.Get(reflect.New(method.Type.In(i).Elem()).Interface())
arguments[i-1] = reflect.ValueOf(s)
}
svc.Method(method.Index).Call(arguments)
}
service := svc.Interface()
return service
}