golang-uber-dig

bởi samber

Implements dependency injection in Golang using uber-go/dig — reflection-based container, Provide/Invoke, dig.In/dig.Out parameter and result objects, named values, value groups, optional dependencies, scopes, and Decorate. Apply when using or adopting uber-go/dig, when the codebase imports `go.uber.org/dig`, or when wiring an application graph at startup. For higher-level lifecycle and modules, see `samber/cc-skills-golang@golang-uber-fx` skill.

npx skills add https://github.com/samber/cc-skills-golang --skill golang-uber-dig

Persona: You are a Go architect wiring an application graph with dig. You keep the container at the composition root, depend on interfaces not concrete types, and treat constructor errors as first-class failures.

Using uber-go/dig for Dependency Injection in Go

Reflection-based DI toolkit, designed to power application frameworks (it is the engine behind uber-go/fx) and resolve object graphs during startup.

Official Resources:

This skill is not exhaustive. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform.

go get go.uber.org/dig

dig vs. fx

fx is built on dig and shares the same container engine — the DI primitives (Provide, Invoke, In/Out structs, named values, value groups) are identical. fx.In/fx.Out are re-exports of dig.In/dig.Out.

What fx adds on top of dig:

Concerndigfx
DI containerdig.New()✅ (embedded)
Lifecycle hooksfx.Lifecycle OnStart/OnStop
Module systemfx.Module with scoped decorators
Signal-aware run loopapp.Run() blocks on SIGINT/SIGTERM
Structured event loggingfx.WithLogger / fxevent
Startup/shutdown timeoutfx.StartTimeout / fx.StopTimeout

Choose dig when you need the wiring graph only: CLI tools, libraries exposing a container to callers, test harnesses, or embedding DI into an existing app that manages its own lifecycle.

Choose fx for long-running services (HTTP servers, workers, daemons) — lifecycle and signal handling are non-negotiable there. See samber/cc-skills-golang@golang-uber-fx skill.

Container

import "go.uber.org/dig"

c := dig.New()

Useful options: dig.DeferAcyclicVerification() (faster startup), dig.RecoverFromPanics() (turn panics into dig.PanicError), dig.DryRun(true) (validate without invoking).

Provide and Invoke

// Register a constructor — lazy, only runs when its output is needed
err := c.Provide(func(cfg *Config) (*sql.DB, error) {
    return sql.Open("postgres", cfg.DSN)
})

// Pull a service out of the container by asking for it as a function parameter
err = c.Invoke(func(db *sql.DB) error {
    return db.Ping()
})

Constructors are lazy and memoized: each output type is built once and shared (singleton per container). Provide errors at registration if the constructor is malformed; Invoke returns the constructor's error wrapped with the dependency path that triggered it.

A dig constructor is any function. Inputs are dependencies, outputs are provided types. error (last return) signals construction failure. Follow "accept interfaces, return structs".

Parameter Objects with dig.In

Once a constructor has 4+ dependencies, embed dig.In to group them as struct fields and tag fields:

type HandlerParams struct {
    dig.In

    Logger *zap.Logger
    DB     *sql.DB
    Cache  *redis.Client `optional:"true"`           // zero value if not provided
    DBRO   *sql.DB       `name:"readonly"`           // named dependency
    Routes []http.Handler `group:"routes"`           // value group
}

func NewHandler(p HandlerParams) *Handler { /* ... */ }

Tags: name:"...", optional:"true", group:"...".

Result Objects with dig.Out

Return several values from one constructor and attach name/group tags to results:

type ConnResult struct {
    dig.Out

    ReadWrite *sql.DB `name:"primary"`
    ReadOnly  *sql.DB `name:"readonly"`
}

func NewConnections(cfg *Config) (ConnResult, error) { /* ... */ }

Named Values

Two providers of the same type collide. Disambiguate with dig.Name:

c.Provide(NewPrimaryDB,  dig.Name("primary"))
c.Provide(NewReadOnlyDB, dig.Name("readonly"))

Consume by adding name:"primary" / name:"readonly" to a dig.In field.

Value Groups

Many providers, one consumer slice — typical for HTTP handlers, health checks, migrations:

type RouteResult struct {
    dig.Out
    Handler http.Handler `group:"routes"`
}

func NewUserHandler(db *sql.DB) RouteResult { /* ... */ }
func NewPostHandler(db *sql.DB) RouteResult { /* ... */ }

type ServerParams struct {
    dig.In
    Routes []http.Handler `group:"routes"`
}

Flatten — append ,flatten (e.g. group:"routes,flatten") to unwrap a slice instead of nesting it. Group order is not guaranteed; if order matters, provide an explicit ordered slice from a single constructor.

Provide as Interface (dig.As)

Register a concrete constructor and expose it under one or more interfaces without a separate adapter:

c.Provide(NewPostgresDB, dig.As(new(Database), new(io.Closer)))
// Consumers ask for Database or io.Closer; *PostgresDB stays hidden.

Full Application Example

func main() {
    c := dig.New()

    must(c.Provide(NewConfig))
    must(c.Provide(NewLogger))
    must(c.Provide(NewDatabase))
    must(c.Provide(NewServer))

    err := c.Invoke(func(srv *http.Server) error {
        return srv.ListenAndServe()
    })
    if err != nil {
        log.Fatal(err)
    }
}

func must(err error) { if err != nil { panic(err) } }

dig has no built-in lifecycle. If you need OnStart/OnStop hooks, signal handling, and graceful shutdown, use fx — see samber/cc-skills-golang@golang-uber-fx skill.

For Decorate, Scopes, optional deps, error helpers, and Visualize, see advanced.md.

Best Practices

  1. Keep the container at the composition root — never pass *dig.Container as a parameter; treat it like a plumbing detail of main(). Service-locator patterns defeat the testability gains of DI.
  2. Depend on interfaces, not concrete types — lets you swap implementations in tests without touching production code, and lets you use dig.As to expose narrow interfaces from wide structs.
  3. Prefer parameter objects (dig.In structs) once a constructor has 4+ dependencies — call sites stay readable and adding a new dependency is a one-line change instead of a signature break.
  4. Group registration by module (one file per module that calls c.Provide for its types) — review and refactoring become a per-module concern, and you can extract a module into a fx.Module later without rewriting wiring.
  5. Validate the graph eagerly in tests — call c.Invoke against the composition root in CI to surface missing providers at boot time, not at first request. DryRun(true) skips constructor execution.
  6. Return errors from constructors instead of panicking — dig wraps them with the dependency path, which makes the failure point obvious.

Common Mistakes

MistakeFix
Passing the container into servicesThe container belongs to main(). Inject the typed dependencies a service needs; otherwise tests need to build a real container.
Two providers for the same type without Namedig errors at Provide time. Either name them, or merge into a single provider that returns a dig.Out result struct.
Ignoring Provide errorsWrap each Provide with a must helper. A silent registration error becomes a missing-type error far later.
Using groups when ordering mattersGroups are unordered. If order matters (middleware chain, migration sequence), provide an explicit ordered slice with one constructor.
Constructors with side effects on importKeep init() empty — start work only inside the constructor, after the graph is built.

Testing

dig containers are cheap — build a fresh one per test, override providers with Decorate, and call Invoke to drive the system. For full patterns (per-test wiring, shared helpers, graph validation in CI, asserting wire-time errors, recovering from constructor panics), see testing.md.

Further Reading

  • advanced.md — Decorate, Scopes, optional deps, error helpers, Visualize, full Quick Reference
  • recipes.md — end-to-end examples: HTTP server with route group, two databases, request scopes, decorators, dry-run validation
  • testing.md — testing patterns and graph validation

Cross-References

  • → See samber/cc-skills-golang@golang-uber-fx skill for application lifecycle, modules, and signal-aware Run() built on top of dig
  • → See samber/cc-skills-golang@golang-dependency-injection skill for DI concepts and library comparison
  • → See samber/cc-skills-golang@golang-samber-do skill for a generics-based alternative without reflection
  • → See samber/cc-skills-golang@golang-google-wire skill for compile-time DI (no runtime container)
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for interface design patterns
  • → See samber/cc-skills-golang@golang-testing skill for general testing patterns

If you encounter a bug or unexpected behavior in uber-go/dig, open an issue at https://github.com/uber-go/dig/issues.

Thêm skills từ 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
Các mẫu thiết kế Golang theo phong cách bản địa — tùy chọn hàm, hàm khởi tạo, luồng lỗi và xếp tầng, quản lý tài nguyên và vòng đời, tắt máy an toàn, khả năng phục hồi, kiến trúc, tiêm phụ thuộc, xử lý dữ liệu, truyền phát, v.v. Áp dụng khi lựa chọn rõ ràng giữa các mẫu kiến trúc, triển khai tùy chọn hàm, thiết kế API hàm khởi tạo, thiết lập tắt máy an toàn, áp dụng các mẫu phục hồi, hoặc hỏi mẫu Go bản địa nào phù hợp với một vấn đề cụ thể.
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
Các mẫu và phương pháp tối ưu hiệu năng Golang - nếu X là điểm nghẽn, thì áp dụng Y. Bao gồm giảm cấp phát, hiệu quả CPU, bố trí bộ nhớ, tinh chỉnh GC, pooling, caching, và tối ưu đường dẫn nóng. Sử dụng khi profiling hoặc benchmark đã xác định được điểm nghẽn và bạn cần mẫu tối ưu phù hợp để khắc phục. Cũng sử dụng khi thực hiện đánh giá mã hiệu năng để đề xuất cải tiến hoặc benchmark có thể giúp xác định các cải thiện hiệu năng nhanh chóng. Không dành cho phương pháp đo lường (→...
developmentcode-review
golang-security
samber
Các phương pháp bảo mật tốt nhất và phòng ngừa lỗ hổng cho Golang. Bao gồm injection (SQL, lệnh, XSS), mật mã học, an toàn hệ thống tệp, bảo mật mạng, cookie, quản lý bí mật, an toàn bộ nhớ và ghi nhật ký. Áp dụng khi viết, xem xét hoặc kiểm tra mã Go về bảo mật, hoặc khi làm việc trên bất kỳ mã rủi ro nào liên quan đến mật mã, I/O, quản lý bí mật, xử lý đầu vào người dùng hoặc xác thực. Bao gồm cấu hình các công cụ bảo mật.
securitycode-reviewdevelopment
golang-database
samber
Hướng dẫn toàn diện về truy cập cơ sở dữ liệu Go — truy vấn tham số hóa, quét struct, cột NULL, giao dịch, mức cô lập, SELECT FOR UPDATE, connection pool, xử lý hàng loạt, truyền context và công cụ migration. Sử dụng khi viết, xem xét hoặc gỡ lỗi mã Golang tương tác với PostgreSQL, MariaDB, MySQL hoặc SQLite; để kiểm thử cơ sở dữ liệu; hoặc cho các câu hỏi về database/sql, sqlx hoặc pgx. KHÔNG tạo lược đồ cơ sở dữ liệu hoặc SQL migration.
developmentdatabase
golang-lint
samber
Các phương pháp linting tốt nhất và cấu hình golangci-lint cho các dự án Golang — chạy linters, cấu hình .golangci.yml, loại bỏ cảnh báo bằng chỉ thị nolint, diễn giải đầu ra lint, và lựa chọn linters. Sử dụng khi cấu hình golangci-lint, hỏi về cảnh báo lint hoặc loại bỏ nolint, thiết lập công cụ chất lượng mã, hoặc chọn linters. Cũng sử dụng khi người dùng đề cập đến golangci-lint, go vet, staticcheck, hoặc revive.
developmentcode-reviewtesting