golang-uber-dig
samber/cc-skills-golang
Reflection-based dependency injection for Go using uber-go/dig — wire application graphs at startup with Provide/Invoke and parameter objects.
What is golang-uber-dig?
uber-go/dig is a lightweight DI container for Go that resolves object graphs through reflection. Use it when building CLI tools, libraries, or applications that need constructor-based wiring without lifecycle management. For long-running services requiring OnStart/OnStop hooks and signal handling, use fx instead.
- Register constructors with Provide() and resolve dependencies with Invoke()
- Use dig.In/dig.Out parameter and result objects to manage multiple dependencies cleanly
- Support named values, value groups, and optional dependencies via struct tags
- Expose concrete types as interfaces with dig.As() without adapter boilerplate
- Validate dependency graphs eagerly with DryRun mode to catch wiring errors at startup
- Handle constructor errors as first-class failures with automatic dependency path wrapping
How to install golang-uber-dig
npx skills add https://github.com/samber/cc-skills-golang --skill golang-uber-dig- Go 1.11 or later
- go.uber.org/dig imported in your project (go get go.uber.org/dig)
How to use golang-uber-dig
- 1.Create a dig container with dig.New() at your composition root (typically main())
- 2.Register constructors using c.Provide() for each service or dependency
- 3.Group related providers by module in separate files for clarity
- 4.Use dig.In structs with tags (name, optional, group) for constructors with 4+ dependencies
- 5.Use dig.Out structs with tags to return multiple named or grouped values from one constructor
- 6.Call c.Invoke() to pull services from the container and start your application
- 7.Add validation tests that call c.Invoke() with DryRun(true) to catch wiring errors early
Use cases
- Wiring a CLI application's service graph at startup without lifecycle overhead
- Building a library that exposes a pre-configured dig container to callers
- Setting up test harnesses with swappable mock implementations via interfaces
- Organizing modular Go applications where each module registers its own providers
- Validating dependency graphs in CI before deployment
- Go backend developers building CLI tools or libraries
- Architects designing modular Go applications with constructor-based wiring
- Teams adopting uber-go/dig in existing codebases
- Developers who need lightweight DI without lifecycle/signal handling
golang-uber-dig FAQ
Use dig for CLI tools, libraries, and applications where you manage your own lifecycle. Use fx for long-running services (HTTP servers, workers, daemons) that need OnStart/OnStop hooks, signal handling, and graceful shutdown. fx is built on dig and adds lifecycle management on top.
Keep the container at the composition root (main function) and never pass *dig.Container to other functions. This prevents service-locator anti-patterns and preserves testability. All wiring happens at startup, not at request time.
dig wraps constructor errors with the full dependency path that triggered the failure, making it obvious where the problem occurred. Return errors from constructors instead of panicking so dig can provide this context.
Use dig.Name() to disambiguate providers of the same type, then consume them with name tags in dig.In structs (e.g., name:"primary", name:"readonly"). Alternatively, use value groups with group tags for collections of handlers or plugins.
Yes, add optional:"true" tag to a dig.In field. If no provider exists, the field receives its zero value. This is useful for optional middleware, caches, or feature flags.
Full instructions (SKILL.md)
Source of truth, from samber/cc-skills-golang.
name: golang-uber-dig
description: "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."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.
metadata:
author: samber
version: "1.1.1"
openclaw:
emoji: "⛏"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
skill-library-version: "1.19.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs
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. For Go package docs, versions, symbols, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill.
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:
| Concern | dig | fx |
|---|---|---|
| DI container | ✅ dig.New() | ✅ (embedded) |
| Lifecycle hooks | ❌ | ✅ fx.Lifecycle OnStart/OnStop |
| Module system | ❌ | ✅ fx.Module with scoped decorators |
| Signal-aware run loop | ❌ | ✅ app.Run() blocks on SIGINT/SIGTERM |
| Structured event logging | ❌ | ✅ fx.WithLogger / fxevent |
| Startup/shutdown timeout | ❌ | ✅ fx.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
- Keep the container at the composition root — never pass
*dig.Containeras a parameter; treat it like a plumbing detail ofmain(). Service-locator patterns defeat the testability gains of DI. - Depend on interfaces, not concrete types — lets you swap implementations in tests without touching production code, and lets you use
dig.Asto expose narrow interfaces from wide structs. - Prefer parameter objects (
dig.Instructs) 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. - Group registration by module (one file per module that calls
c.Providefor its types) — review and refactoring become a per-module concern, and you can extract a module into a fx.Module later without rewriting wiring. - Validate the graph eagerly in tests — call
c.Invokeagainst the composition root in CI to surface missing providers at boot time, not at first request.DryRun(true)skips constructor execution. - Return errors from constructors instead of panicking — dig wraps them with the dependency path, which makes the failure point obvious.
Common Mistakes
| Mistake | Fix |
|---|---|
| Passing the container into services | The 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 Name | dig errors at Provide time. Either name them, or merge into a single provider that returns a dig.Out result struct. |
Ignoring Provide errors | Wrap each Provide with a must helper. A silent registration error becomes a missing-type error far later. |
| Using groups when ordering matters | Groups are unordered. If order matters (middleware chain, migration sequence), provide an explicit ordered slice with one constructor. |
| Constructors with side effects on import | Keep 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-fxskill for application lifecycle, modules, and signal-aware Run() built on top of dig - → See
samber/cc-skills-golang@golang-dependency-injectionskill for DI concepts and library comparison - → See
samber/cc-skills-golang@golang-samber-doskill for a generics-based alternative without reflection - → See
samber/cc-skills-golang@golang-google-wireskill for compile-time DI (no runtime container) - → See
samber/cc-skills-golang@golang-structs-interfacesskill for interface design patterns - → See
samber/cc-skills-golang@golang-testingskill 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.
Related skills
More from samber/cc-skills-golang and the wider catalog.
golang-code-style
Go code style conventions for clarity, control flow, and readability—line breaking, variable declarations, and when comments help.
golang-error-handling
Idiomatic Go error handling: wrapping, inspection, structured logging, and production-grade error tracking.
golang-performance
Go performance optimization patterns: identify bottlenecks with profiling, then apply the right fix.
golang-design-patterns
Idiomatic Go design patterns: functional options, constructors, error handling, resource lifecycle, graceful shutdown, and resilience.
golang-testing
Production-ready Go tests with table-driven patterns, testify integration, parallel execution, fuzzing, and leak detection.
golang-security
Security best practices and vulnerability prevention for Go code—injection, crypto, secrets, and authentication.