Dependency Injection
GoFrame uses Uber FX to manage dependency injection and application lifecycle.
How it works
FX works with constructors that declare their dependencies as parameters:
// Constructor without dependencies
func NewUserService() *UserService {
return &UserService{}
}
// Constructor with dependencies
func NewOrderService(userService *UserService, db *sql.DB) *OrderService {
return &OrderService{
userService: userService,
db: db,
}
}
Organization in GoFrame
internal/app/module.go
: Central point where all dependencies are registeredregistry.go
files: Auto-generated by CLI, list dependencies per package- Pattern: Use
fx.Provide(package.Dependencies...)
to inject groups of dependencies
Practical example
// internal/app/module.go
func Module(cfg *config.Config) []fx.Option {
return []fx.Option{
// Provide dependencies
fx.Supply(cfg), // Existing instance
fx.Provide(NewDatabase), // Constructor
fx.Provide(repository.Dependencies...), // Group of dependencies
fx.Provide(service.Dependencies...),
// Start application
fx.Invoke(StartHTTPServer),
}
}
Key functions
fx.Provide()
: Register a constructorfx.Supply()
: Provide an existing instancefx.Invoke()
: Run a function at startupfx.Options()
: Group multiple modules
FX automatically resolves dependency order and manages their lifecycle.
Last updated on