golang-dependency-injection

作者: samber

Go語言中依賴注入(DI)的全面指南。涵蓋DI的重要性(可測試性、鬆散耦合、關注點分離、生命週期管理)、手動建構子注入,以及DI函式庫比較(google/wire、uber-go/dig、uber-go/fx、samber/do)。在設計服務架構、設定依賴注入、重構緊密耦合程式碼、管理單例或服務工廠,或當使用者詢問控制反轉、服務等問題時,使用此技能。

npx skills add https://github.com/samber/cc-skills-golang --skill golang-dependency-injection

Persona: You are a Go software architect. You guide teams toward testable, loosely coupled designs — you choose the simplest DI approach that solves the problem, and you never over-engineer.

Modes:

  • Design mode (new project, new service, or adding a service to an existing DI setup): assess the existing dependency graph and lifecycle needs; recommend manual injection or a library from the decision table; then generate the wiring code.
  • Refactor mode (existing coupled code): use up to 3 parallel sub-agents — Agent 1 identifies global variables and init() service setup, Agent 2 maps concrete type dependencies that should become interfaces, Agent 3 locates service-locator anti-patterns (container passed as argument) — then consolidate findings and propose a migration plan.

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-dependency-injection skill takes precedence.

Dependency Injection in Go

Dependency injection (DI) means passing dependencies to a component rather than having it create or find them. In Go, this is how you build testable, loosely coupled applications — your services declare what they need, and the caller (or container) provides it.

This skill is not exhaustive. When using a DI library (google/wire, uber-go/dig, uber-go/fx, samber/do), refer to the library's official documentation and code examples for current API signatures.

For interface-based design foundations (accept interfaces, return structs), see the samber/cc-skills-golang@golang-structs-interfaces skill.

Best Practices Summary

  1. Dependencies MUST be injected via constructors — NEVER use global variables or init() for service setup
  2. Small projects (< 10 services) SHOULD use manual constructor injection — no library needed
  3. Interfaces MUST be defined where consumed, not where implemented — accept interfaces, return structs
  4. NEVER use global registries or package-level service locators
  5. The DI container MUST only exist at the composition root (main() or app startup) — NEVER pass the container as a dependency
  6. Prefer lazy initialization — only create services when first requested
  7. Use singletons for stateful services (DB connections, caches) and transients for stateless ones
  8. Mock at the interface boundary — DI makes this trivial
  9. Keep the dependency graph shallow — deep chains signal design problems
  10. Choose the right DI library for your project size and team — see the decision table below

Why Dependency Injection?

Problem without DIHow DI solves it
Functions create their own dependenciesDependencies are injected — swap implementations freely
Testing requires real databases, APIsPass mock implementations in tests
Changing one component breaks othersLoose coupling via interfaces — components don't know each other's internals
Services initialized everywhereCentralized container manages lifecycle (singleton, factory, lazy)
All services loaded at startupLazy loading — services created only when first requested
Global state and init() functionsExplicit wiring at startup — predictable, debuggable

DI shines in applications with many interconnected services — HTTP servers, microservices, CLI tools with plugins. For a small script with 2-3 functions, manual wiring is fine. Don't over-engineer.

Manual Constructor Injection (No Library)

For small projects, pass dependencies through constructors. See Manual DI examples for a complete application example.

// ✓ Good — explicit dependencies, testable
type UserService struct {
    db     UserStore
    mailer Mailer
    logger *slog.Logger
}

func NewUserService(db UserStore, mailer Mailer, logger *slog.Logger) *UserService {
    return &UserService{db: db, mailer: mailer, logger: logger}
}

// main.go — manual wiring
func main() {
    logger := slog.Default()
    db := postgres.NewUserStore(connStr)
    mailer := smtp.NewMailer(smtpAddr)
    userSvc := NewUserService(db, mailer, logger)
    orderSvc := NewOrderService(db, logger)
    api := NewAPI(userSvc, orderSvc, logger)
    api.ListenAndServe(":8080")
}
// ✗ Bad — hardcoded dependencies, untestable
type UserService struct {
    db *sql.DB
}

func NewUserService() *UserService {
    db, _ := sql.Open("postgres", os.Getenv("DATABASE_URL")) // hidden dependency
    return &UserService{db: db}
}

Manual DI breaks down when:

  • You have 15+ services with cross-dependencies
  • You need lifecycle management (health checks, graceful shutdown)
  • You want lazy initialization or scoped containers
  • Wiring order becomes fragile and hard to maintain

DI Library Comparison

Go has three main approaches to DI libraries:

Decision Table

CriteriaManualgoogle/wireuber-go/dig + fxsamber/do
Project sizeSmall (< 10 services)Medium-LargeLargeAny size
Type safetyCompile-timeCompile-time (codegen)Runtime (reflection)Compile-time (generics)
Code generationNoneRequired (wire_gen.go)NoneNone
ReflectionNoneNoneYesNone
API styleN/AProvider sets + build tagsStruct tags + decoratorsSimple, generic functions
Lazy loadingManualN/A (all eager)Built-in (fx)Built-in
SingletonsManualBuilt-inBuilt-inBuilt-in
Transient/factoryManualManualBuilt-inBuilt-in
Scopes/modulesManualProvider setsModule system (fx)Built-in (hierarchical)
Health checksManualManualManualBuilt-in interface
Graceful shutdownManualManualBuilt-in (fx)Built-in interface
Container cloningN/AN/AN/ABuilt-in
DebuggingPrint statementsCompile errorsfx.Visualize()ExplainInjector(), web interface
Go versionAnyAnyAny1.18+ (generics)
Learning curveNoneMediumHighLow

Quick Comparison: Same App, Four Ways

The dependency graph: Config -> Database -> UserStore -> UserService -> API

Manual:

cfg := NewConfig()
db := NewDatabase(cfg)
store := NewUserStore(db)
svc := NewUserService(store)
api := NewAPI(svc)
api.Run()
// No automatic shutdown, health checks, or lazy loading

google/wire:

// wire.go — then run: wire ./...
func InitializeAPI() (*API, error) {
    wire.Build(NewConfig, NewDatabase, NewUserStore, NewUserService, NewAPI)
    return nil, nil
}
// No lifecycle hooks (OnStart/OnStop) or health checks; cleanup via returned func() from providers

uber-go/fx:

app := fx.New(
    fx.Provide(NewConfig, NewDatabase, NewUserStore, NewUserService),
    fx.Invoke(func(api *API) { api.Run() }),
)
app.Run() // manages lifecycle, but reflection-based

samber/do:

i := do.New()
do.Provide(i, NewConfig)
do.Provide(i, NewDatabase)    // auto shutdown + health check
do.Provide(i, NewUserStore)
do.Provide(i, NewUserService)
api := do.MustInvoke[*API](i)
api.Run()
// defer i.Shutdown() — handles all cleanup automatically

Testing with DI

DI makes testing straightforward — inject mocks instead of real implementations:

// Define a mock
type MockUserStore struct {
    users map[string]*User
}

func (m *MockUserStore) FindByID(ctx context.Context, id string) (*User, error) {
    u, ok := m.users[id]
    if !ok {
        return nil, ErrNotFound
    }
    return u, nil
}

// Test with manual injection
func TestUserService_GetUser(t *testing.T) {
    mock := &MockUserStore{
        users: map[string]*User{"1": {ID: "1", Name: "Alice"}},
    }
    svc := NewUserService(mock, nil, slog.Default())

    user, err := svc.GetUser(context.Background(), "1")
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    if user.Name != "Alice" {
        t.Errorf("got %q, want %q", user.Name, "Alice")
    }
}

Testing with samber/do — Clone and Override

Container cloning creates an isolated copy where you override only the services you need to mock:

func TestUserService_WithDo(t *testing.T) {
    // Create a test injector with mock implementation
    testInjector := do.New()

    // Provide the mock UserStore interface
    do.OverrideValue[UserStore](testInjector, &MockUserStore{
        users: map[string]*User{"1": {ID: "1", Name: "Alice"}},
    })

    // Provide other real services as needed
    do.Provide[*slog.Logger](testInjector, func(i *do.Injector) (*slog.Logger, error) {
        return slog.Default(), nil
    })

    svc := do.MustInvoke[*UserService](testInjector)
    user, err := svc.GetUser(context.Background(), "1")
    // ... assertions
}

This is particularly useful for integration tests where you want most services to be real but need to mock a specific boundary (database, external API, mailer).

When to Adopt a DI Library

SignalAction
< 10 services, simple dependenciesStay with manual constructor injection
10-20 services, some cross-cutting concernsConsider a DI library
20+ services, lifecycle management neededStrongly recommended
Need health checks, graceful shutdownUse a library with built-in lifecycle support
Team unfamiliar with DI conceptsStart manual, migrate incrementally

Common Mistakes

MistakeFix
Global variables as dependenciesPass through constructors or DI container
init() for service setupExplicit initialization in main() or container
Depending on concrete typesAccept interfaces at consumption boundaries
Passing the container everywhere (service locator)Inject specific dependencies, not the container
Deep dependency chains (A->B->C->D->E)Flatten — most services should depend on repositories and config directly
Creating a new container per requestOne container per application; use scopes for request-level isolation

Cross-References

  • → See samber/cc-skills-golang@golang-samber-do skill for detailed samber/do usage patterns
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for interface design and composition
  • → See samber/cc-skills-golang@golang-testing skill for testing with dependency injection
  • → See samber/cc-skills-golang@golang-project-layout skill for DI initialization placement

References

來自 samber 的更多技能

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
符合慣例的 Golang 設計模式 — 函數選項、建構子、錯誤流程與串聯、資源管理與生命週期、優雅關閉、韌性、架構、依賴注入、資料處理、串流等。適用於明確選擇架構模式、實作函數選項、設計建構子 API、設定優雅關閉、應用韌性模式,或詢問哪種慣用 Go 模式適合特定問題時。
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Golang 性能優化模式與方法論 - 若遇到 X 瓶頸,則應用 Y。涵蓋減少分配、CPU 效率、記憶體佈局、GC 調校、池化、快取以及熱路徑優化。適用於當性能分析或基準測試已識別出瓶頸,且需要正確的優化模式來解決時。亦適用於進行性能代碼審查時,提出改進建議或可協助快速識別性能增益的基準測試。不適用於測量方法論(→...
developmentcode-review
golang-security
samber
Golang的安全最佳實踐與漏洞防範。涵蓋注入攻擊(SQL、命令、XSS)、密碼學、檔案系統安全、網路安全、Cookie、機密管理、記憶體安全及日誌記錄。適用於撰寫、審查或稽核Go程式碼的安全性,或處理涉及加密、I/O、機密管理、使用者輸入處理或身分驗證的高風險程式碼。包含安全工具的配置。
securitycode-reviewdevelopment
golang-database
samber
Go 資料庫存取的全面指南 — 參數化查詢、結構掃描、可空欄位、交易、隔離層級、SELECT FOR UPDATE、連線池、批次處理、上下文傳遞與遷移工具。適用於撰寫、審查或除錯與 PostgreSQL、MariaDB、MySQL 或 SQLite 互動的 Golang 程式碼;資料庫測試;或關於 database/sql、sqlx 或 pgx 的問題。不產生資料庫結構或遷移 SQL。
developmentdatabase
golang-lint
samber
針對 Golang 專案的 lint 最佳實務與 golangci-lint 配置 — 執行 linter、設定 .golangci.yml、使用 nolint 指令抑制警告、解讀 lint 輸出,以及選擇 linter。適用於配置 golangci-lint、詢問 lint 警告或 nolint 抑制方式、設定程式碼品質工具,或挑選 linter 時。亦適用於使用者提及 golangci-lint、go vet、staticcheck 或 revive 時。
developmentcode-reviewtesting