Using Google Wire for Dependency Injection in Go
This article explains the concept of dependency injection, demonstrates a simple Go example with Message, Greeter, and Event components, and shows how the Google Wire library can automate the wiring of these components through code generation, reducing manual initialization complexity.
When a project grows, the number of dependencies and their initialization order can make the main function hard to maintain, so a dependency injection (DI) framework is useful.
DI is a design pattern that lets an object receive the other objects it depends on, separating concerns, reducing coupling, and improving testability compared with the traditional approach where a client creates service instances directly.
Below is a minimal Go example that follows DI principles. It defines a Message type, a Greeter that holds a Message , and an Event that holds a Greeter . Each component has a constructor function.
type Message string
type Greeter struct {
Message Message // <- adding a Message field
}
type Event struct {
Greeter Greeter
}
func NewMessage() Message {
return Message("Hi there!")
}
func NewGreeter(m Message) Greeter {
return Greeter{Message: m}
}
func NewEvent(g Greeter) Event {
return Event{Greeter: g}
}
func (g Greeter) Greet() Message {
return g.Message
}
func (e Event) Start() {
msg := e.Greeter.Greet()
fmt.Println(msg)
}
func main() {
message := NewMessage()
greeter := NewGreeter(message)
event := NewEvent(greeter)
event.Start()
}To avoid the repetitive manual wiring, the Google Wire library can generate the initialization code. First, the main function is simplified to call an injected initializer:
func main() {
e := InitializeEvent()
e.Start()
}In a separate wire.go file, an injector function is defined using wire.Build to list the providers:
//+build wireinject
package main
import "github.com/google/wire"
func InitializeEvent() Event {
wire.Build(NewEvent, NewGreeter, NewMessage)
return Event{}
}After installing Wire with go install github.com/google/wire/cmd/wire@latest and running wire in the source directory, Wire generates wire_gen.go containing the concrete wiring:
func InitializeEvent() Event {
message := NewMessage()
greeter := NewGreeter(message)
event := NewEvent(greeter)
return event
}This generated code is functionally identical to the manual version but scales effortlessly to larger projects, illustrating how Wire simplifies dependency injection in Go backend applications.
360 Smart Cloud
Official service account of 360 Smart Cloud, dedicated to building a high-quality, secure, highly available, convenient, and stable one‑stop cloud service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.