uber-go/fx

Multiple implementations

Juandavi1 opened this issue · 3 comments

Hi ! Awesome project ! I love it 🥵.

Do you know how to implement something similar to profiles in Spring Boot, but with FX?

The concept of profiles allows having multiple implementations of the same interface, but at runtime, only one dependency is available based on a configuration parameter. For example, implementing different versions based on country.

Could you please explain how to achieve this?

Thanks a lot !!

lEx0 commented

The easiest way to achieve this is by using a flag that can be obtained through configuration or a command-line argument.

fx.New(
	fx.Provide(
		func() string {
			var country string
			// parse config
			return country
		},
	),
	fx.Provide(
		func(country string) CountryInterface {
			switch country {
			case "us":
				return NewUS()
			case "uk":
				return NewUK()
			default:
				return NewDefault()
			}
		},
	),
)

It is also recommended not to use plain strings for representing the country value in fx. Instead, it's better to use a separate custom type or use name tag

That's right, but it is not we want to do.
If we have multiple implementations of multiple types we will end up with switch cases everywhere :(

Hi! Temporarily, we resolved the request with the following approach.

image

And perform some validations.

image