inject
inject copied to clipboard
Resolving named interfaces as map[<name>]<interface>
Problem
In case, when I have several named implementations of an interface, I need a simple and clean way to get needed implementation by name.
For example, I have two writer types: file
and s3
.
inject.New(
inject.Provide(file.NewDestination, inject.As(new(writer.Destination)), inject.WithName("file")),
inject.Provide(s3.NewDestination, inject.As(new(writer.Destination)), inject.WithName("s3")),
)
And I need to resolve concrete writer by name.
Proposal
For named providers that will be injected as interfaces create map[<name>]<interface>
group.
// NewDestinationWriter
func NewDestinationWriter(destinations map[string]writer.Destination) *DestinationWriter {
return &DestinationWriter{
destinations: destinations,
}
}
// DestinationWriter writes data to destination.
type DestinationWriter {
destinations map[string]writer.Destination
}
// WriteTo writes data to destination by its name.
func (w *DestinationWriter) WriteTo(destination string, data []byte) error {
writer, ok := w.destinations[destination]
if !ok {
return fmt.Errorf("destination %s not found", destination)
}
return writer.WriteBytes(data)
}