Nov 18, 20268 min read

Dependency Injection in Go: Constructors, Wire, Fx and Service Structs

How to pass dependencies into Go services so they are easy to test: plain constructors, interfaces for fakes, Uber's Fx container, what happened to Google Wire, and Encore service structs with initService.

Illustration for Dependency Injection in Go: Constructors, Wire, Fx and Service Structs

Go has no dependency injection framework in the standard library, and most Go code does not need one: a type takes what it depends on as constructor arguments or struct fields, main builds everything once, and tests pass fakes through small interfaces. The pattern is plain Go, and it scales further than people expect.

The friction shows up at the edges of that pattern. main grows into a long wiring function that every new endpoint touches, startup and shutdown order for servers and pools becomes its own code, and calls between services need a seam for tests that a package-level function call does not give you.

This guide shows constructor injection in plain Go, then Uber's Fx container and the state of Google Wire, and starts with Encore's service structs, where the framework calls your init function and other services call your endpoints through generated functions.

Go dependency injection options at a glance

Encore service structsConstructor injectionUber FxGoogle Wire
WiringinitService() per service, called by EncoreBy hand in mainProvider functions resolved at runtimeCode generated at build time
Startup and shutdownHandled by the runtimeYour codeLifecycle hooksYour code
Missing dependencyCompile error in your init codeCompile errorError when the app startsBuild error from wire
Faking for testsBuild the struct with fakes, et.MockEndpoint, et.MockServicePass fakes to constructorsfx.Replace or fx.Decorate in test appsPass fakes to providers
Status in 2026MaintainedPlain GoMaintainedArchived, no longer maintained

How does dependency injection work with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and in Go it handles dependency injection with a service struct: a type marked //encore:service holds the service's dependencies, and an initService function builds them once when the service starts, much like main in a plain program. Endpoints are methods on that struct, and Encore generates package-level functions so other services keep calling them as notify.SendReceipt(ctx, ...) without knowing about the struct.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create billing --example=hello-world$ cd billing && mkdir notify

Depend on an interface

The receipt service only needs to send one email, so its dependency is a one-method interface. The production implementation calls Postmark's email API with a token from an Encore secret:

// notify/sender.go package notify import ( "bytes" "context" "encoding/json" "fmt" "net/http" ) // Sender is the one thing the service needs from an email provider. type Sender interface { Send(ctx context.Context, to, subject, body string) error } // postmarkSender sends through Postmark's email API. type postmarkSender struct { token string from string client *http.Client } func (p *postmarkSender) Send(ctx context.Context, to, subject, body string) error { payload, err := json.Marshal(map[string]string{ "From": p.from, "To": to, "Subject": subject, "TextBody": body, }) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.postmarkapp.com/email", bytes.NewReader(payload)) if err != nil { return err } req.Header.Set("Accept", "application/json") req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Postmark-Server-Token", p.token) resp, err := p.client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("postmark: unexpected status %d", resp.StatusCode) } return nil }

Wire it in initService

The service struct holds the sender and a clock, which makes the receipt date testable too. initService is the only place that knows about Postmark:

// notify/notify.go package notify import ( "context" "fmt" "net/http" "strings" "time" "encore.dev/beta/errs" ) var secrets struct { PostmarkServerToken string } //encore:service type Service struct { sender Sender now func() time.Time } // initService runs once when the service starts, like main in a plain Go program. func initService() (*Service, error) { return &Service{ sender: &postmarkSender{ token: secrets.PostmarkServerToken, from: "billing@example.com", client: &http.Client{Timeout: 10 * time.Second}, }, now: time.Now, }, nil } type ReceiptParams struct { Email string `json:"email"` OrderID string `json:"order_id"` AmountCents int64 `json:"amount_cents"` } // SendReceipt emails a payment receipt. Other services call it as notify.SendReceipt. // //encore:api private method=POST path=/notify/receipt func (s *Service) SendReceipt(ctx context.Context, p *ReceiptParams) error { if !strings.Contains(p.Email, "@") || p.OrderID == "" || p.AmountCents <= 0 { return &errs.Error{Code: errs.InvalidArgument, Message: "email, order_id and a positive amount are required"} } body := fmt.Sprintf("Order %s: $%d.%02d paid on %s.", p.OrderID, p.AmountCents/100, p.AmountCents%100, s.now().UTC().Format("2006-01-02")) return s.sender.Send(ctx, p.Email, "Your receipt for order "+p.OrderID, body) }

Test with a fake

A test builds the struct itself, with a fake sender and a fixed clock, and calls the method directly. encore test ./... runs it like go test, with the app compiled the way encore run compiles it:

// notify/notify_test.go package notify import ( "context" "testing" "time" ) type fakeSender struct{ sent []string } func (f *fakeSender) Send(_ context.Context, to, subject, body string) error { f.sent = append(f.sent, to+" | "+subject+" | "+body) return nil } func TestSendReceipt(t *testing.T) { fake := &fakeSender{} svc := &Service{ sender: fake, now: func() time.Time { return time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC) }, } err := svc.SendReceipt(context.Background(), &ReceiptParams{ Email: "ada@example.com", OrderID: "o-42", AmountCents: 1990, }) if err != nil { t.Fatal(err) } want := "ada@example.com | Your receipt for order o-42 | Order o-42: $19.90 paid on 2026-11-18." if len(fake.sent) != 1 || fake.sent[0] != want { t.Fatalf("sent %q, want %q", fake.sent, want) } } func TestSendReceiptRejectsBadInput(t *testing.T) { svc := &Service{sender: &fakeSender{}, now: time.Now} if err := svc.SendReceipt(context.Background(), &ReceiptParams{Email: "nope"}); err == nil { t.Fatal("expected an error") } }

When the code under test lives in another service, such as an orders endpoint that calls notify.SendReceipt, the test does not need a seam of its own: et.MockEndpoint(notify.SendReceipt, fn) swaps the endpoint for that test and its subtests, and et.MockService("notify", obj) swaps the whole service. Infrastructure follows the same idea: databases, caches and topics are declared as package variables, and encore test gives each run its own test database instead of a constructor argument.

That layout also suits coding agents: the dependency an agent adds goes into one initService, the test that proves it builds the struct next to it, and encore test runs it without anyone wiring a container.

Best fit: Go backends with several services, where you want each service's dependencies in one init function, calls between services mockable in tests, and startup handled by the runtime.

How do you do dependency injection in plain Go?

Constructors and Uber Fx

Constructor injection needs no library. Each component takes its dependencies as arguments and main builds the graph in order, so the compiler catches anything missing:

func main() { log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) db, err := sql.Open("pgx", os.Getenv("DATABASE_URL")) if err != nil { log.Error("open db", "err", err) os.Exit(1) } defer db.Close() sender := &postmarkSender{token: os.Getenv("POSTMARK_SERVER_TOKEN"), from: "billing@example.com", client: &http.Client{Timeout: 10 * time.Second}} receipts := &ReceiptHandler{db: db, sender: sender} mux := http.NewServeMux() mux.Handle("POST /receipts", receipts) log.Error("server stopped", "err", http.ListenAndServe(":8080", mux)) }

That stays readable for a handful of components. When there are dozens, each with startup and shutdown work, Uber Fx takes the same constructors as providers, resolves the graph when the app starts, and runs OnStart and OnStop hooks in dependency order:

// main.go (go.uber.org/fx v1.24.0) func NewDB(lc fx.Lifecycle) (*sql.DB, error) { db, err := sql.Open("pgx", os.Getenv("DATABASE_URL")) if err != nil { return nil, err } lc.Append(fx.Hook{OnStop: func(context.Context) error { return db.Close() }}) return db, nil } func NewServer(lc fx.Lifecycle, h *ReceiptHandler) *http.Server { mux := http.NewServeMux() mux.Handle("POST /receipts", h) srv := &http.Server{Addr: ":8080", Handler: mux} lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { ln, err := net.Listen("tcp", srv.Addr) if err != nil { return err } go srv.Serve(ln) return nil }, OnStop: func(ctx context.Context) error { return srv.Shutdown(ctx) }, }) return srv } func main() { fx.New( fx.Provide(NewLogger, NewDB, NewSender, NewReceiptHandler, NewServer), fx.Invoke(func(*http.Server) {}), ).Run() }

The trade-off is that Fx finds a missing provider when the app starts rather than when it compiles. Google Wire solved that by generating the wiring at build time, but the repository is archived and its README now says the project is no longer maintained, so a new codebase should not start on it; existing Wire providers are ordinary constructors and can be called from hand-written wiring. In every plain Go setup, the database, the secrets and the environment variables in main still have to exist locally and in each environment.

Best fit: constructor injection for most Go services, and Fx for large binaries with many components that need ordered startup and shutdown.

How to choose

Start with constructor injection in plain Go, and keep the interfaces small and owned by the code that uses them. Move to Fx when main is mostly lifecycle code, and avoid starting new projects on Wire. Pick Encore when you are building a Go backend with several services, and you want dependencies wired per service in initService, cross-service calls that tests can mock with one line, and the database and secrets those dependencies use provisioned locally and in your own AWS or GCP account.

Frequently asked questions

Do you need a dependency injection framework in Go?

No. Go code normally uses constructor injection: each type takes its dependencies as constructor arguments or struct fields, main wires them together once, and tests pass fakes that satisfy small interfaces. A container such as Uber Fx starts to pay off when dozens of components need ordered startup and shutdown.

Is Google Wire still maintained?

No. The google/wire repository is archived and its README says the project is no longer maintained, with changes expected to happen in forks. Code written for Wire is ordinary constructor functions, so it keeps working if you replace the generated injector with hand-written wiring.

What is the difference between Wire and Fx?

Wire generated the wiring code at build time from provider functions, so a missing dependency failed the build. Fx resolves the dependency graph at runtime with reflection when the app starts, and adds lifecycle hooks for starting and stopping components such as servers and database pools.

How does dependency injection work in Encore for Go?

Declare a struct with //encore:service and an initService function that builds its dependencies, then define endpoints as methods on the struct. Encore calls initService when the service starts. In tests you construct the struct yourself with fakes, and et.MockEndpoint or et.MockService replace calls to other services.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders