Go (Golang) Tutorial 0/45 lessons ~6 min read Lesson 38

    Dependency Injection

    Go has no built-in DI framework like .NET — dependency injection is explicit constructor injection.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Go has no built-in DI framework like .NET — dependency injection is explicit constructor injection. Pass dependencies as struct fields set in constructor functions; accept interfaces for testability. Wire, fx, and dig provide compile-time or runtime containers for larger apps.

    Clean architecture in Go: main.go wires concrete implementations to handlers; services depend on repository interfaces; tests inject mocks. Interviewers ask how you test HTTP handlers and swap database implementations without frameworks.

    This lesson wires handler → service → repository manually — the pattern used in most Go microservices before reaching for Wire code generation.

    The story

    Uber's Go microservices wire dependencies in main: construct a database pool, pass it to a repository, inject the repository into a service, and attach the service to HTTP handlers. Constructor functions like NewPaymentService(repo Repository, logger *slog.Logger) make dependencies explicit — no hidden globals, easy to swap fakes in tests.

    Frameworks like Wire (Google) codegen dependency graphs, but manual constructor injection remains the most readable pattern for small and medium services.

    Understanding the topic

    Key concepts

    • Constructor injection: NewService(repo Repository) *Service.
    • Depend on interfaces defined by consumer package.
    • main.go composition root — only place knowing all concretes.
    • google/wire compile-time DI code generation.
    • uber/fx runtime DI with lifecycle hooks.
    • Avoid global singletons — pass dependencies explicitly.
    Visual overview
    Client → Server
    HTTP Request
    Server → Handler
    ServeHTTP
    Handler → Service
    Business Logic
    Service → DB
    Query
    DB → Handler
    Data
    Handler → Client
    JSON Response

    Step-by-step explanation

    1. Define Repository interface in service package.
    2. PostgresRepo implements Repository with *sql.DB.
    3. Service struct holds Repository interface field.
    4. NewService injects repo via constructor parameter.
    5. Handler holds *Service; main wires: repo → svc → handler.
    6. Tests pass mockRepository to NewService.

    Practical code example

    Manual DI wiring handler, service, and repository in main:

    go
    package main
    import (
    "context"
    "fmt"
    "net/http"
    )
    type UserRepository interface {
    FindByID(ctx context.Context, id string) (string, error)
    }
    type postgresUserRepo struct{}
    func (postgresUserRepo) FindByID(ctx context.Context, id string) (string, error) {
    return "Alice", nil
    }
    type UserService struct {
    repo UserRepository
    }
    func NewUserService(repo UserRepository) *UserService {
    return &UserService{repo: repo}
    }
    func (s *UserService) GetName(ctx context.Context, id string) (string, error) {
    return s.repo.FindByID(ctx, id)
    }
    type UserHandler struct {
    svc *UserService
    }
    func NewUserHandler(svc *UserService) *UserHandler {
    return &UserHandler{svc: svc}
    }
    func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    name, err := h.svc.GetName(r.Context(), r.URL.Query().Get("id"))
    if err != nil {
    http.Error(w, err.Error(), 500)
    return
    }
    fmt.Fprintln(w, name)
    }
    func main() {
    repo := postgresUserRepo{}
    svc := NewUserService(repo)
    handler := NewUserHandler(svc)
    http.ListenAndServe(":8080", handler)
    }

    Line-by-line code explanation

    • type UserRepository interface { describes what the service needs from a repository: a FindByID method. The service depends on this interface, not on a concrete type.
    • func (postgresUserRepo) FindByID(ctx context.Context, id string) (string, error) { is a concrete implementation. Despite its name it does not touch a database here; it ignores both arguments and always returns Alice with no error.
    • repo UserRepository is the field in UserService that holds the dependency. Because its type is the interface, any type with a matching FindByID method can be stored here.
    • func NewUserService(repo UserRepository) *UserService { is a constructor that receives the repository from the caller instead of creating one itself. This is constructor injection.
    • func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { gives UserHandler the method that http.Handler requires, so a *UserHandler can be passed to the HTTP server directly.
    • name, err := h.svc.GetName(r.Context(), r.URL.Query().Get("id")) calls the service with the request's context and the id query parameter, for example from /?id=7.
    • http.Error(w, err.Error(), 500) replies with status 500 and the error text if the service returns an error. With this example repository that branch is never reached.
    • fmt.Fprintln(w, name) writes the returned name, followed by a newline, to the response.
    • http.ListenAndServe(":8080", handler) serves on port 8080. The lines above it in main wire everything together: the repository goes into the service and the service into the handler.

    Key takeaway: main is composition root. Service accepts interface — swap postgresUserRepo for mock in tests. No global state.

    Real-world use

    Where you'll use this in production

    • Swapping Postgres for in-memory repo in unit tests.
    • Multi-implementation payment processors (Stripe, PayPal).
    • Feature flag injected config service.
    • Wire-generated wiring in large monorepos.

    Best practices

    • Constructor functions for every injectable type.
    • Interface at consumer, implementation in infrastructure package.
    • Keep main.go as only composition root.
    • Avoid service locator and global variables.
    • Use Wire when manual wiring exceeds ~20 lines.
    • Document lifecycle: who closes DB connections.

    Common mistakes

    • Concrete types everywhere — untestable handlers.
    • Init() functions creating global DB connection.
    • Circular dependencies between packages.
    • Over-using DI framework for 3-component app.
    • Interface on wrong side — producer defines giant interface.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionDI in Go without Spring?+

    Answer

    Constructor injection; interfaces; main wires concretes.
    2BeginnerQuestionWhy inject interfaces?+

    Answer

    Swap implementations in tests; decouple layers.
    3IntermediateQuestionWire vs manual DI?+

    Answer

    Wire generates wiring code compile-time; manual fine for small apps.
    4IntermediateQuestionComposition root?+

    Answer

    main package — only place importing all layers and constructing graph.
    5AdvancedQuestionTest HTTP handler with mocked service.+

    Answer

    Mock UserRepository; NewUserService(mock); httptest against NewUserHandler(svc).

    Summary

    Go DI is explicit constructor injection via interfaces. main.go is the composition root wiring all dependencies. Accept interfaces in services; return concrete from constructors. Wire/fx help scale DI; manual wiring fine for small services. Next lesson: configuration management.

    Ready to mark this lesson complete?Track your journey across the entire course.