fx icon indicating copy to clipboard operation
fx copied to clipboard

Multiple implementations

Open Juandavi1 opened this issue 2 years ago • 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 !!

Juandavi1 avatar Jun 19 '23 04:06 Juandavi1

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

lEx0 avatar Jun 19 '23 05:06 lEx0

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 :(

Juandavi1 avatar Jun 19 '23 05:06 Juandavi1

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

image

And perform some validations.

image

Juandavi1 avatar Jun 21 '23 21:06 Juandavi1