Load retrieves and constructs a component by its name, ensuring it matches the expected type T. It returns an error if the component is not found, if there is a type mismatch, or if construction fails.
(name string, args ...any)
| 102 | // Load retrieves and constructs a component by its name, ensuring it matches the expected type T. |
| 103 | // It returns an error if the component is not found, if there is a type mismatch, or if construction fails. |
| 104 | func Load[T any](name string, args ...any) (T, error) { |
| 105 | muComponents.RLock() |
| 106 | defer muComponents.RUnlock() |
| 107 | |
| 108 | var zeroVal T |
| 109 | component, exists := components[name] |
| 110 | if !exists { |
| 111 | return zeroVal, fmt.Errorf("component with name %q does not exists", name) |
| 112 | } |
| 113 | |
| 114 | targetType := reflect.TypeFor[T]() |
| 115 | definition := component.Definition() |
| 116 | sourceType := definition.Type() |
| 117 | if !convertibleTo(sourceType, targetType) { |
| 118 | return zeroVal, fmt.Errorf("mismatched type for component with name %q", name) |
| 119 | } |
| 120 | |
| 121 | out, err := definition.Constructor().Invoke(args...) |
| 122 | if err != nil { |
| 123 | return zeroVal, err |
| 124 | } |
| 125 | |
| 126 | return out.(T), nil |
| 127 | } |
| 128 | |
| 129 | // List returns all registered components as a slice. |
| 130 | func List() []*Component { |
nothing calls this directly
no test coverage detected