How to correctly slim down provide calls
I'm trying to understand if I'm setting up my app.Run() correctly. I have a variety of controllers I need to initialize in my application who themselves require inputs like a logger, config etc
app := fx.New(
fx.Provide(
config.NewConfig,
logger.NewLogger,
metrics.NewMetrics,
db.NewDb,
controllers.NewUserController,
controllers.NewEventController,
controllers.NewTripController,
router.NewRouter,
),
fx.Invoke(RegisterServer),
)
Controllers file
package controllers
func NewUserController(logger *zap.Logger, config *viper.Config) (*UserController, error) {
....
}
Is there a good mechanism to wrap all the controller Constructors into one function such that this fx.Provide function doesn't get increasingly large as I add new controllers?
I could define a NewControllers method which returns an fx.Out object but I'm having trouble understanding how I could inject the logger and config dependencies without explicilty having to do so
@rssathe
Fx options are composable, meaning multiple Provide/Invoke functions can be combined together into one option.
They way we use it ourselves is by exporting a "module" (just convention naming, can be anything) from different parts of the application to tie it all together.
For example:
controllers/controllers.go
package controllers
var Module = fx.Provide(
NewController1,
NewController2,
NewController3,
NewEtc...
)
handlers/handlers.go
package handlers
var Module = fx.Options(
fx.Provide(NewHandler1),
fx.Provide(NewHandler2),
fx.Invoke(SomeInvokeFucntion()),
)
main.go
package main
import contorllers
import handlers
import fx
func main() {
fx.New(
controllers.Module,
handlers.Module,
.. any other funcs and/or options ..
)
)
Fx options can be composed more, if needed. For example, combining multiple modules into one that is exposed into main.
Going to optimistically resolve the issue, hoping that my answer helps. Please feel free to reopen if it's not what you were looking for, or have follow up questions.