Skip to content

Is it possible to use multiple implementations for a given interface type? #956

Answered by abhinav
ag9920 asked this question in Q&A
Discussion options

You must be logged in to vote

Hello! Yes, you can do that with named values.

When you provide each implementation, give it a name by either using fx.Out, or fx.Annotate.
If your constructor returns the struct rather than the interface, you can use fx.Annotate to also adjust that.

// Given,
type Doer interface{ ... }

// And three implementations,
type GoodDoer struct{ ... }
func NewGoodDoer() *GoodDoer

type BadDoer struct{ ... }
func NewBadDoer() *BadDoer

type UglyDoer struct{ ... }
func NewUglyDoer() *UglyDoer

fx.Provide(
  fx.Annotate(NewGoodDoer, fx.As(new(Doer)), fx.ResultTags(`name:"good"`)),
  fx.Annotate(NewBadDoer, fx.As(new(Doer)), fx.ResultTags(`name:"bad"`)),
  fx.Annotate(NewUglyDoer, fx.As(new(Doer)), fx.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by sywhang
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants