-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.go
40 lines (32 loc) · 976 Bytes
/
provider.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
package module
import "context"
// Provider is the interface to provide an Instance.
type Provider interface {
key() moduleKey
value(ctx context.Context) (any, error)
}
// BuildFunc is the constructor of an Instance.
type BuildFunc[T any] func(context.Context) (T, error)
type funcProvider[T any] struct {
moduleKey moduleKey
ctor BuildFunc[T]
}
// ProvideWithFunc returns a provider which provides instances creating from `ctor` function.
func (m Module[T]) ProvideWithFunc(ctor BuildFunc[T]) Provider {
return &funcProvider[T]{
moduleKey: m.moduleKey,
ctor: ctor,
}
}
// ProvideValue returns a provider which always provides given `value` as instances.
func (m Module[T]) ProvideValue(value T) Provider {
return m.ProvideWithFunc(func(context.Context) (T, error) {
return value, nil
})
}
func (p funcProvider[T]) key() moduleKey {
return p.moduleKey
}
func (p funcProvider[T]) value(ctx context.Context) (any, error) {
return p.ctor(ctx)
}