-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
89 lines (72 loc) · 1.95 KB
/
service.go
File metadata and controls
89 lines (72 loc) · 1.95 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
83
84
85
86
87
88
89
package red
import (
"errors"
"fmt"
"reflect"
)
func (c *Container) Register(service any) error {
c.mu.Lock()
defer c.mu.Unlock()
val := reflect.ValueOf(service)
typ := val.Type()
// Check if it's a zero-arg constructor: func() (*T, error)
if typ.Kind() == reflect.Func &&
typ.NumIn() == 0 &&
typ.NumOut() == 2 &&
containsError(typ) {
results := val.Call(nil)
if !results[1].IsNil() {
err := results[1].Interface().(error)
return fmt.Errorf("red: %w", err)
}
instance := results[0]
instanceType := instance.Type()
if _, exists := c.instances[instanceType]; exists {
return errors.New("red: service already registered")
}
c.instances[instanceType] = instance
return nil
}
// Standard: registering a concrete instance directly
if _, exists := c.instances[typ]; exists {
return errors.New("red: service already registered")
}
c.instances[typ] = val
return nil
}
func (c *Container) Locate(target any) error {
ptr := reflect.ValueOf(target)
if ptr.Kind() != reflect.Ptr || ptr.IsNil() {
return errors.New("red: locatable target must be a non-nil pointer")
}
targetType := ptr.Elem().Type()
if instance, ok := c.instances[targetType]; ok {
ptr.Elem().Set(instance)
return nil
}
if provider, ok := c.providers[targetType]; ok {
c.im.Lock()
instance, err := c.invokeProvider(provider)
c.im.Unlock()
if err != nil {
return fmt.Errorf("red: %w", err)
}
ptr.Elem().Set(instance)
// Cache the instance
c.instances[targetType] = instance
return nil
}
return errors.New("red: no instance or provider found")
}
// invokeProvider executes a provider function and checks for returned error
func (c *Container) invokeProvider(provider reflect.Value) (reflect.Value, error) {
args, err := c.invokeWithDeps(provider)
if err != nil {
return reflect.Value{}, err
}
results := provider.Call(args)
if !results[1].IsNil() {
return reflect.Value{}, results[1].Interface().(error)
}
return results[0], nil
}