Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple implementations #1096

Open
Juandavi1 opened this issue Jun 19, 2023 · 3 comments
Open

Multiple implementations #1096

Juandavi1 opened this issue Jun 19, 2023 · 3 comments
Labels

Comments

@Juandavi1
Copy link

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
Copy link

lEx0 commented Jun 19, 2023

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

@Juandavi1
Copy link
Author

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
Copy link
Author

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

image

And perform some validations.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

3 participants