-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer.go
More file actions
82 lines (64 loc) · 1.63 KB
/
container.go
File metadata and controls
82 lines (64 loc) · 1.63 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package red
import (
"errors"
"fmt"
"reflect"
)
func (c *Container) provide(provider any) error {
c.mu.Lock()
defer c.mu.Unlock()
val := reflect.ValueOf(provider)
typ := val.Type()
if typ.Kind() != reflect.Func || typ.NumOut() != 2 {
return errors.New("red: provider must be a function that has two return values")
}
if !containsError(typ) {
return errors.New("red: second return value of provider must be error")
}
outType := typ.Out(0)
if _, exists := c.providers[outType]; exists {
return errors.New("red: provider is already registered")
}
c.providers[outType] = val
return nil
}
func (c *Container) invoke(fn any) error {
val := reflect.ValueOf(fn)
c.im.Lock()
args, err := c.invokeWithDeps(val)
if err != nil {
return fmt.Errorf("red: %w", err)
}
c.im.Unlock()
results := val.Call(args)
if !results[0].IsNil() {
return fmt.Errorf("red: %w", results[0].Interface().(error))
}
return nil
}
func (c *Container) invokeWithDeps(fn reflect.Value) ([]reflect.Value, error) {
typ := fn.Type()
args := make([]reflect.Value, typ.NumIn())
for i := 0; i < typ.NumIn(); i++ {
argType := typ.In(i)
c.mu.RLock()
instance, ok := c.instances[argType]
provider, hasProvider := c.providers[argType]
c.mu.RUnlock()
if !ok {
if !hasProvider {
return nil, fmt.Errorf("missing dependency of type %v", argType)
}
newInstance, err := c.invokeProvider(provider)
if err != nil {
return nil, fmt.Errorf("failed to invoke provider for %v: %w", argType, err)
}
c.mu.Lock()
c.instances[argType] = newInstance
c.mu.Unlock()
instance = newInstance
}
args[i] = instance
}
return args, nil
}