forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoption.go
91 lines (78 loc) · 2.28 KB
/
option.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
83
84
85
86
87
88
89
90
91
package container
import (
"reflect"
"github.com/pkg/errors"
)
// Option is a functional option for a container.
type Option interface {
apply(*container) error
}
// Provide creates a container option which registers the provided dependency
// injection constructors. Each constructor will be called at most once with the
// exception of scoped constructors which are called at most once per scope
// (see Scope).
func Provide(constructors ...interface{}) Option {
return containerOption(func(ctr *container) error {
return provide(ctr, nil, constructors)
})
}
// ProvideWithScope creates a container option which registers the provided dependency
// injection constructors that are to be run in the provided scope. Each constructor
// will be called at most once.
func ProvideWithScope(scopeName string, constructors ...interface{}) Option {
return containerOption(func(ctr *container) error {
if scopeName == "" {
return errors.Errorf("expected non-empty scope name")
}
return provide(ctr, ctr.createOrGetScope(scopeName), constructors)
})
}
func provide(ctr *container, scope Scope, constructors []interface{}) error {
for _, c := range constructors {
rc, err := ExtractProviderDescriptor(c)
if err != nil {
return errors.WithStack(err)
}
_, err = ctr.addNode(&rc, scope)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func Supply(values ...interface{}) Option {
loc := LocationFromCaller(1)
return containerOption(func(ctr *container) error {
for _, v := range values {
err := ctr.supply(reflect.ValueOf(v), loc)
if err != nil {
return errors.WithStack(err)
}
}
return nil
})
}
// Error creates an option which causes the dependency injection container to
// fail immediately.
func Error(err error) Option {
return containerOption(func(*container) error {
return errors.WithStack(err)
})
}
// Options creates an option which bundles together other options.
func Options(opts ...Option) Option {
return containerOption(func(ctr *container) error {
for _, opt := range opts {
err := opt.apply(ctr)
if err != nil {
return errors.WithStack(err)
}
}
return nil
})
}
type containerOption func(*container) error
func (c containerOption) apply(ctr *container) error {
return c(ctr)
}
var _ Option = (*containerOption)(nil)