-
Notifications
You must be signed in to change notification settings - Fork 0
/
autowire.go
64 lines (50 loc) · 1.7 KB
/
autowire.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
package autowire
import (
"context"
"fmt"
)
// Build builds object for the specified type within a container
func Build[T any](c Container, opts ...ContextOption) (value T, err error) {
targetType := typeFor[T]()
val, err := c.Build(targetType, opts...)
if err != nil {
return value, err
}
value, ok := val.Interface().(T)
if !ok { // this should never happen
return value, fmt.Errorf("%w: unable to cast result as type '%v'", ErrTypeCast, targetType)
}
return value, nil
}
// BuildWithCtx builds object for the specified type within a container.
// This function will pass the specified context object to every provider that requires a context.
func BuildWithCtx[T any](ctx context.Context, c Container, opts ...ContextOption) (value T, err error) {
targetType := typeFor[T]()
val, err := c.BuildWithCtx(ctx, targetType, opts...)
if err != nil {
return value, err
}
value, ok := val.Interface().(T)
if !ok { // this should never happen
return value, fmt.Errorf("%w: unable to cast result as type '%v'", ErrTypeCast, targetType)
}
return value, nil
}
// Get gets object of a type within a container.
// If no object is created for the type or `sharedMode` is `false`, ErrNotFound is returned.
func Get[T any](c Container) (value T, err error) {
targetType := typeFor[T]()
val, err := c.Get(targetType)
if err != nil {
return value, err
}
value, ok := val.Interface().(T)
if !ok { // this should never happen
return value, fmt.Errorf("%w: unable to cast result as type '%v'", ErrTypeCast, targetType)
}
return value, nil
}
// Resolve builds dependency graph for the specified type within a container
func Resolve[T any](c Container) (DependencyGraph, error) {
return c.Resolve(typeFor[T]())
}