Compile-time dependency injection for Go using annotations.
go install github.com/eloonstra/autowire@latestRun directly:
autowire --out ./cmd --scan ./internal --scan ./pkgor via go generate (for example in cmd/main.go):
//go:generate autowire --scan ../internal --scan ../pkg//autowire:provide
func NewConfig() *Config { ... }
//autowire:provide
func NewDatabase(cfg *Config) (*Database, error) { ... }
//autowire:provide
type Server struct {
Config *Config // injected (exported fields only)
}
//autowire:invoke
func SetupRoutes(svc *UserService) error { ... }//autowire:provide: registers a single type as injectable (functions or structs)//autowire:invoke: calls a function during initialization for side effects
Functions can optionally return an error.
Bind a provider to an interface instead of its concrete type:
//autowire:provide Reader
func NewFileReader() *FileReader { ... }For interfaces from other packages, import the package and use the package alias:
import "io"
var _ io.Writer = (*BufferedWriter)(nil) // compile-time check
//autowire:provide io.Writer
func NewBufferedWriter() *BufferedWriter { ... }Adding var _ interfaces.Interface = (*Implementation)(nil) is recommended. it verifies at compile time that your type
implements the interface and prevents "imported and not used" errors.
InterfaceName: interface in same packagepackage.InterfaceName: imported interface (requires import)
Generates app_gen.go with an App struct containing all providers and an InitializeApp() function that wires
everything in dependency order:
func main() {
app, err := InitializeApp()
if err != nil {
panic(err)
}
app.Server.Start()
}| autowire | wire (archived) | do | Fx | |
|---|---|---|---|---|
| Compile-time safe | ✓ | ✓ | ✓ | |
| Code generation | ✓ | ✓ | ||
| No manual wiring | ✓ | |||
| Struct injection | ✓ | |||
| Zero runtime cost | ✓ | ✓ | ||
| Cycle detection | ✓ | ✓ | ✓ | ✓ |
| Interface binding | ✓ | ✓ | ✓ | ✓ |
| Lifecycle hooks | ✓ | ✓ | ||
| Named dependencies | soon™ | ✓ | ✓ | ✓ |