Golang / GoLang System Architecture and Testing Interview Questions
How do you manage dependency injection at scale in a large Go service — wire, dig, or manual?
As a Go service grows beyond a few dependencies, main() becomes a complex wiring function. Three approaches: manual wiring (always readable), Google Wire (code generation), or Uber Dig (reflection-based runtime injection).
// APPROACH 1: Manual wiring in main() — clear, no magic, preferred for < 20 deps
func main() {
cfg, err := config.Load()
if err != nil { log.Fatal(err) }
db, err := database.Open(cfg.Database)
if err != nil { log.Fatal(err) }
userRepo := postgres.NewUserRepository(db)
emailSvc := smtp.NewEmailService(cfg.SMTP)
cacheSvc := redis.NewCache(cfg.Redis)
userSvc := service.NewUserService(userRepo, emailSvc, cacheSvc)
grpcSrv := grpc.NewUserServer(userSvc)
httpSrv := http.NewServer(cfg.HTTP, userSvc)
// Start servers...
}
// APPROACH 2: Wire (google/wire) — compile-time code generation
// wire.go (build tag: //go:build wireinject)
//go:build wireinject
func InitializeApp(cfgPath string) (*App, func(), error) {
wire.Build(
config.Provider, // func LoadConfig() (*Config, error)
database.Provider, // func Open(*Config) (*sql.DB, error)
postgres.NewUserRepository,
smtp.NewEmailService,
service.NewUserService,
NewApp,
)
return nil, nil, nil // wire generates the real implementation
}
// Run: wire gen ./... → generates wire_gen.go
// APPROACH 3: Dig (uber-go/dig) — runtime reflection-based DI
container := dig.New()
container.Provide(config.Load)
container.Provide(database.Open)
container.Provide(postgres.NewUserRepository)
container.Provide(service.NewUserService)
container.Invoke(func(svc *service.UserService) {
// svc is fully constructed with all deps injected
startServer(svc)
})Trade-offs: Manual wiring is the most debuggable (stack traces show actual constructor calls). Wire generates readable code at compile time (fails fast, zero runtime overhead). Dig is most concise but uses reflection (runtime errors, harder to trace). The Go community generally prefers manual or Wire over Dig for production services.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
