Skip to content

[Question] How do I provide 2 different instances of the same type? #902

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

You must be logged in to vote

Hello! You can indeed do that in Fx too.
In Fx, we call this "named values".

There are a couple ways to produce and consumed named values.

Producing named values

Result objects

Result objects are structs that embed fx.Out respectively.
You tag fields of such a struct with name:".." to have it produce a named value.

For example, to produce named values, you would write constructors in the following form,

type ReadOnlyResult struct {
  Conn *db.Conn `name:"ro"`
}

func connectReadOnly() ReadOnlyResult {
  // ...
}

type ReadWriteResult struct {
  Conn *db.Conn `name:"rw"`
}

func connectReadWrite() ReadOnlyResult {
  // ...
}

And then fx.Provide them as usual:

var Module = fx.Provide(connec…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by abhinav
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
Converted from issue

This discussion was converted from issue #901 on July 26, 2022 20:19.