Introduction
Uber Fx is a dependency injection framework for Go that eliminates manual wiring of application components. Developed at Uber to manage the complexity of large Go microservices, it automatically resolcts constructor dependencies, manages component lifecycles, and handles graceful startup and shutdown sequences.
What Uber Fx Does
- Resolves constructor dependencies automatically using Go's type system
- Manages application lifecycle with ordered startup and shutdown hooks
- Groups related providers into reusable modules
- Validates the entire dependency graph at startup before serving traffic
- Supports named and grouped dependencies for advanced wiring patterns
Architecture Overview
Fx uses a container that accepts constructor functions (providers) and builds a directed acyclic graph of dependencies based on their input and output types. When the application starts, Fx instantiates components in dependency order, runs lifecycle hooks, and blocks until a shutdown signal arrives. On shutdown, it tears down components in reverse order, ensuring clean resource release.
Self-Hosting & Configuration
- Install with
go get go.uber.org/fxin any Go module - Register constructors using
fx.Provide()in thefx.New()call - Use
fx.Invoke()to trigger side effects like starting an HTTP server - Add lifecycle hooks with
fx.Lifecyclefor startup and shutdown logic - Organize providers into
fx.Module()groups for modular applications
Key Features
- Type-based automatic dependency resolution with no tags or annotations
- Lifecycle management with ordered start/stop hooks and graceful shutdown
- Dependency graph validation catches wiring errors before the app serves traffic
- Module system for organizing large applications into composable units
- Built-in integration with Uber's Zap logger for structured debug output
Comparison with Similar Tools
- Google Wire — compile-time code generation approach; Fx uses runtime reflection for more flexibility
- dig (Uber) — the underlying container library; Fx adds lifecycle management and application framework on top
- manual wiring — works for small apps but becomes unwieldy in large codebases with many dependencies
- Google Guice — Java DI framework; Fx brings similar patterns to Go with idiomatic Go conventions
FAQ
Q: Does Fx use code generation? A: No. Fx resolves dependencies at runtime using Go's type system and reflection, requiring no code generation step.
Q: How does Fx handle errors during startup? A: If any provider or lifecycle hook returns an error, Fx stops startup, tears down any already-started components, and reports the error.
Q: Can I use Fx for small applications? A: Yes, but the benefits are most noticeable in larger applications with many interconnected components. For simple apps, manual wiring may be sufficient.
Q: Is Fx used in production at Uber? A: Yes. Fx was developed at Uber specifically to manage the dependency graphs of their Go microservices and is used extensively in production.