go-uber-fx
Application framework and dependency injection with uber-go/fx. Covers lifecycle hooks, modules, and modular application design.
SKILL.mdskills/go/go-uber-fx/SKILL.md
GitHubCore Concepts
Uber Fx is a framework built on top of the dig DI container. It provides:
- Dependency Injection: Automatic wiring of your application graph.
- Lifecycle Management: Hooks for starting and stopping your application safely.
- Modularity: A way to group related logic into reusable
fx.Moduleunits. - Signal Handling: Automatic handling of termination signals (SIGINT, SIGTERM) for graceful shutdown.
Best Practices
- Keep
main()Thin — Yourmain()function should ideally just be anfx.New(...).Run()call. Push all logic into providers and modules. - Use Lifecycle Hooks — Never start long-running processes (like HTTP servers) in a constructor. Use
lc.Append(fx.Hook{ OnStart: ..., OnStop: ... })instead. - Respect Contexts — Both
OnStartandOnStopreceive acontext.Context. Respect it for timeouts and cancellation. - OnStart Should Not Block — If you need to start a long-running process, spawn a goroutine inside
OnStartand return immediately so the rest of the application can boot. - Annotate for Interfaces — Use
fx.Asto tell Fx that a concrete type should be provided as an interface. - Group Related Providers — Use
fx.Moduleto group related services (e.g., aDatabaseModulecontaining connection pooling and repositories).
Lifecycle Hook Example
func NewServer(lc fx.Lifecycle, logger *log.Logger) *http.Server {
srv := &http.Server{Addr: ":8080"}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
logger.Println("Starting server...")
go srv.ListenAndServe() // Non-blocking!
return nil
},
OnStop: func(ctx context.Context) error {
logger.Println("Stopping server...")
return srv.Shutdown(ctx)
},
})
return srv
}
Modular Design Example
var DBModule = fx.Module("db",
fx.Provide(NewDBConnection, NewUserRepository),
)
func main() {
fx.New(
DBModule,
fx.Provide(NewServer, NewLogger),
fx.Invoke(func(s *http.Server) {
// This triggers the wiring of the server
}),
).Run()
}
Why Uber Fx?
- Boilerplate Reduction: No need to manually wire dozens of services.
- Reliable Shutdown: Ensures all resources (DB, files, sockets) are closed in the correct order.
- Consistency: Enforces a standard way to structure Go applications across a team.
Anti-patterns
- ❌ Blocking
OnStart— Prevents the application from completing its boot cycle. - ❌ Side Effects in Constructors — Don't open connections or start timers in
NewXXXfunctions; use lifecycle hooks. - ❌ Global
fx.App— Don't pass the app itself as a dependency. - ❌ Missing
fx.Invoke— If nothing "invokes" your dependency chain, Fx won't build it. - ❌ Ignoring
OnStopErrors — If a cleanup operation fails, you should log it or handle it; don't silently ignore it.