Replies: 2 comments 7 replies
-
Hey @debedb. The idea is to use Fx to build the configuration object, the logger, and the application. All such dependencies should be parameters to the constructor, and the constructors should be orchestrated through Hypothetically, from what you're suggesting, you might have a function to load configuration, and one to build a logger from that configuration: func LoadConfig() (*Config, error) { /* ... */ }
func NewLogger(*Config) *Logger { /* ... */ } With Fx, you won't call the constructors directly. You'll fx.New(
fx.Provide(
LoadConfig,
NewLogger,
),
) Fx will inspect their signatures and match the func NewApplication(*Config, *Logger) *App
// And then in fx.New:
fx.New(
fx.Provide(
// ..
NewApplication,
),
) Finally, fx.Provide just tells everything "how to build things" but it doesn't yet build anything. To actually do something, you have to tell Fx what you want to actually run. For example, if // Start starts the application in a background goroutine,
// listening on the port specified in Config.
func (*App) Start() error Then you'll add an fx.New(
// ...
fx.Invoke(func(app *App, lc fx.Lifecycle) error {
lc.Append(fx.Hook{
OnStart: func(context.Context) error {
return app.Start()
},
})
}),
)
// There's also a "stop" lifecycle hook that I've omitted above.
// I agree that the hooks API is a bit verbose;
// Fx now includes a better way to do that,
// but I wanted to avoid introducing new concepts right now. Following that, you have to just fx.New(
// ...
).Run() Fx will block until you give it the signal to shutdown. There's an end-to-end tutorial of these features of Fx at https://uber-go.github.io/fx/get-started/. I recommend going over it when you have a chance. |
Beta Was this translation helpful? Give feedback.
-
Yes, sure, but in your example, how do other components refer to the logger or config? |
Beta Was this translation helpful? Give feedback.
-
One of the tenets of this library is:
My question is, what is the blessed pattern to keep some things that are indeed global (say, in my application, it is a config object and logger)? I am currently using Fx to populate a struct containing them but it is a global
var
in a package, which doesn't seem like the best way. What are some best practices?Beta Was this translation helpful? Give feedback.
All reactions