-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.go
54 lines (40 loc) · 886 Bytes
/
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
package bandaid
import (
"context"
"errors"
"fmt"
"sync"
)
type ObjectID string
type IoCContainer struct {
sync.RWMutex
objects map[ObjectID]interface{}
}
var (
Container = &IoCContainer{
objects: make(map[ObjectID]interface{}),
}
)
func (c *IoCContainer) Fetch(ctx context.Context, name ObjectID) interface{} {
c.RLock()
defer c.RUnlock()
if c.objects[name] == nil {
panic(fmt.Sprintf("no object named %s found in the container", name))
}
obj := c.objects[name]
return obj
}
func (c *IoCContainer) Assign(ctx context.Context, name ObjectID, obj interface{}) error {
c.Lock()
defer c.Unlock()
if c.objects[name] != nil {
return errors.New("object already exists with the same name")
}
c.objects[name] = obj
return nil
}
func (c *IoCContainer) Clear(ctx context.Context) {
c.Lock()
defer c.Unlock()
c.objects = make(map[ObjectID]interface{})
}