A Go service grows into a constellation of pgxpool.Pool, *http.Client, Logger, Cache, EventBus, etc. — and a single main.go wiring them by hand becomes 300 lines of constructor chains. Wire generates that wiring at compile time from a small declarative definition, leaving runtime overhead at zero and turning DI mistakes into compile errors. This article shows how Stack Harbor uses Wire on production Go services.
How to verify
After running wire, you have a generated file you commit:
go install github.com/google/wire/cmd/wire@latest
wire ./...
ls cmd/api/
cat cmd/api/wire_gen.go | head -20
go build ./...
wire reads wire.go in the package and writes wire_gen.go next to it. The generated file is normal Go you commit and review like any other.
What’s happening
Wire is a code generator. You write a function annotated with //go:build wireinject that returns the top-level type you want assembled. Inside, you call wire.Build(...) and pass a list of provider expressions — functions, structs, or wire.NewSet(...) groupings. Wire reads that function, computes the dependency graph, and writes a real implementation of the function into wire_gen.go. The annotated source is excluded from the normal build by the build tag.
The model is the inverse of runtime DI containers (Java Spring, .NET DI, Python dependency-injector). Runtime containers resolve types from a registry at startup, paying for reflection and risking missing-binding errors at request time. Wire resolves the graph at go generate time — if a provider is missing or the graph has a cycle, you get a compile error.
Providers compose. A wire.NewSet(NewLogger, NewDB, NewServer) is a reusable bundle. Tests substitute a provider set with a mock set, leaving the rest of the graph identical. Interfaces are bound with wire.Bind(new(InterfaceType), new(*ConcreteType)).
The procedure
-
Install Wire.
go install github.com/google/wire/cmd/wire@latest -
Write provider functions in their natural packages. Each constructor returns a concrete type (and optionally an error):
// internal/db/pg.go package db import ( "context" "github.com/jackc/pgx/v5/pgxpool" ) func NewPool(ctx context.Context, cfg Config) (*pgxpool.Pool, error) { return pgxpool.New(ctx, cfg.URL) }Same shape for
NewLogger,NewServer, etc. They are normal Go functions — Wire calls them in dependency order. -
Group providers into sets. A
wire.NewSetper logical bundle:// internal/db/wire.go package db import "github.com/google/wire" var Set = wire.NewSet(NewPool, NewMigrator)// internal/server/wire.go package server import "github.com/google/wire" var Set = wire.NewSet(NewServer, NewRouter, wire.Bind(new(Handler), new(*router))) -
Write the top-level injector. A
wire.goincmd/api/that returns the assembled app://go:build wireinject // +build wireinject package main import ( "context" "github.com/google/wire" "example.com/internal/db" "example.com/internal/server" "example.com/internal/config" ) func initApp(ctx context.Context, cfg config.Config) (*server.Server, func(), error) { wire.Build( db.Set, server.Set, config.Set, ) return nil, nil, nil }The
func()return is a cleanup function — Wire collects everycleanupreturned by providers and chains them. Call it on shutdown to close pools and flush logs. -
Generate the wiring.
cd cmd/api wireThis writes
wire_gen.go://go:build !wireinject // +build !wireinject package main func initApp(ctx context.Context, cfg config.Config) (*server.Server, func(), error) { pool, err := db.NewPool(ctx, cfg.DB) if err != nil { return nil, nil, err } migrator := db.NewMigrator(pool) _ = migrator router := server.NewRouter(pool) srv, err := server.NewServer(cfg.Server, router) if err != nil { return nil, func() { pool.Close() }, err } return srv, func() { srv.Close(); pool.Close() }, nil }Commit
wire_gen.go. Re-runwirewhenever you change providers; ago:generatedirective at the top ofwire.gomakes it part of the build://go:generate wire -
Wire the main function.
func main() { ctx := context.Background() cfg := config.Load() srv, cleanup, err := initApp(ctx, cfg) if err != nil { log.Fatal(err) } defer cleanup() log.Fatal(srv.Run()) }That is it — every constructor was called in the right order, every dependency was injected, and the cleanup is bound to defer.
-
Substitute mocks in tests. A test creates a parallel injector that uses a mock set:
//go:build wireinject package main_test import "github.com/google/wire" func initTestApp() (*server.Server, error) { wire.Build( db.MockSet, // returns *MockPool server.Set, config.TestSet, ) return nil, nil }Running
wire ./...again generates the test wiring next to it.
Common pitfalls
- Forgetting to re-run
wire. Adding a new provider but skippingwireleaveswire_gen.gostale and the build fails on missing types. Wire togo generate ./...in pre-commit. - Two providers with the same return type. Wire cannot decide between them and the build fails with “multiple bindings”. Either remove the duplicate or use
wire.Value/wire.InterfaceValueto disambiguate. - Circular dependencies. Wire detects cycles at generation time and errors. The fix is the same as in any architecture — break the cycle with an interface or a mediator.
wire.Buildcannot be partial. The function body has exactly one call towire.Buildand areturn nil, nil, nil. No logic before it.- Generated file gets committed badly.
wire_gen.goshould be reviewed like any code, andwire.goexcluded from the main build via thewireinjecttag.
Stack Harbor uses Wire on every Go service we maintain past a few hundred lines — the readability win of a generated wire_gen.go is enormous compared to runtime DI containers that hide failures until startup. See how that fits into the managed operations practice we run for clients.