Skip to content
This repository has been archived by the owner on Jan 18, 2021. It is now read-only.

Resolving named interfaces as map[<name>]<interface> #38

Open
defval opened this issue Dec 16, 2019 · 0 comments
Open

Resolving named interfaces as map[<name>]<interface> #38

defval opened this issue Dec 16, 2019 · 0 comments
Assignees
Labels
enhancement New feature or request v2 Version 2.x.x

Comments

@defval
Copy link
Owner

defval commented Dec 16, 2019

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)
}
@defval defval added enhancement New feature or request v2 Version 2.x.x labels Dec 16, 2019
@defval defval self-assigned this Dec 16, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request v2 Version 2.x.x
Projects
None yet
Development

No branches or pull requests

1 participant