-
Notifications
You must be signed in to change notification settings - Fork 14
/
scope.go
82 lines (64 loc) · 2.35 KB
/
scope.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
package dingo
import (
"reflect"
"sync"
)
type (
// Scope defines a scope's behaviour
Scope interface {
ResolveType(t reflect.Type, annotation string, unscoped func(t reflect.Type, annotation string, optional bool) (reflect.Value, error)) (reflect.Value, error)
}
identifier struct {
t reflect.Type
a string
}
// SingletonScope is our Scope to handle Singletons
// todo use RWMutex for proper locking
SingletonScope struct {
mu sync.Mutex // lock guarding instaceLocks
instanceLock map[identifier]*sync.RWMutex // lock guarding instances
instances sync.Map
}
// ChildSingletonScope manages child-specific singleton
ChildSingletonScope SingletonScope
)
var (
// Singleton is the default SingletonScope for dingo
Singleton Scope = NewSingletonScope()
// ChildSingleton is a per-child singleton, means singletons are scoped and local to an injector instance
ChildSingleton Scope = NewChildSingletonScope()
)
// NewSingletonScope creates a new singleton scope
func NewSingletonScope() *SingletonScope {
return &SingletonScope{instanceLock: make(map[identifier]*sync.RWMutex)}
}
// NewChildSingletonScope creates a new child singleton scope
func NewChildSingletonScope() *ChildSingletonScope {
return &ChildSingletonScope{instanceLock: make(map[identifier]*sync.RWMutex)}
}
// ResolveType resolves a request in this scope
func (s *SingletonScope) ResolveType(t reflect.Type, annotation string, unscoped func(t reflect.Type, annotation string, optional bool) (reflect.Value, error)) (reflect.Value, error) {
ident := identifier{t, annotation}
// try to get the instance type lock
s.mu.Lock()
if l, ok := s.instanceLock[ident]; ok {
// we have the instance lock
s.mu.Unlock()
l.RLock()
defer l.RUnlock()
instance, _ := s.instances.Load(ident)
return instance.(reflect.Value), nil
}
s.instanceLock[ident] = new(sync.RWMutex)
l := s.instanceLock[ident]
l.Lock()
s.mu.Unlock()
instance, err := unscoped(t, annotation, false)
s.instances.Store(ident, instance)
defer l.Unlock()
return instance, err
}
// ResolveType delegates to SingletonScope.ResolveType
func (c *ChildSingletonScope) ResolveType(t reflect.Type, annotation string, unscoped func(t reflect.Type, annotation string, optional bool) (reflect.Value, error)) (reflect.Value, error) {
return (*SingletonScope)(c).ResolveType(t, annotation, unscoped)
}