Golang Uber Dig
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The golang-uber-dig skill provides guidance and patterns for using the uber-go/dig library to manage dependency injection in Go. It covers the core container mechanics, including constructor registration, dependency resolution, parameter and result objects, named values, and value groups. This skill is designed for developers who need to wire application graphs at startup and prefer a reflection-based approach to managing object lifecycles.
What it does
- Registers constructors for lazy dependency injection using Provide.
- Resolves object graphs and executes logic using Invoke.
- Groups dependencies using dig.In and dig.Out structs.
- Handles complex wiring scenarios with named values and value groups.
- Exposes concrete types as interfaces using dig.As.
- Supports advanced features like decorators and child scopes for modularity.
When to use it
- When you need to wire an application graph at startup.
- When building CLI tools or libraries that require a dependency container.
- When you need to manage complex dependency relationships in a Go application.
- When you want to decouple component creation from application logic.
Advantages
- Reduces manual wiring boilerplate in complex applications.
- Enforces clean architecture by encouraging dependency on interfaces.
- Provides clear error reporting with dependency paths upon failure.
- Supports modular design through scopes and decorators.
Usage examples
- “How do I register a database connection in my dig container?”
- You use c.Provide(func() (*sql.DB, error) { ... }) to register the constructor, which dig will call lazily when a component requires the *sql.DB type.
- “How can I group multiple HTTP handlers into a single slice for my server?”
- You use the dig.Group tag in a result struct (dig.Out) to tag each handler, then consume them in a parameter struct (dig.In) as a slice using the same group tag.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/samber/golang-uber-dig/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-uber-dig.zip -d .agents/skills
Documentation by samber
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 — refer to library documentation and code examples for more information:
For Go package docs, symbols, versions, importers, and known vulnerabilities, → See
samber/cc-skills-golang@golang-pkg-go-devskill (godig), preferred over Context7 for Go package facts.To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See
samber/cc-skills-golang@golang-goplsskill (gopls).Context7 remains a fallback for docs not indexed on pkg.go.dev.
go get go.uber.org/digdig 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 whose inputs are dependencies and whose 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.
Files
- ATTRIBUTION.mdAdded by AutoGineer902 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md10.4 KiB
- evals/evals.json12.1 KiB
- references/advanced.md4.9 KiB
- references/recipes.md7.3 KiB
- references/testing.md3.9 KiB
references/recipes.md
Recipes — uber-go/dig
End-to-end examples that go beyond the SKILL.md basics. Each recipe is self-contained and shows a real wiring problem.
Table of Contents
HTTP server with route group
Two databases (read-write + read-only)
Provide as interface (
dig.As) to hide concrete typesRequest-scoped dependencies
Optional dependency for graceful degradation
Decorate to add cross-cutting behavior
DryRun for graph validation in tests
Visualizing a failed graph
HTTP server with route group
package main
import (
"fmt"
"log"
"net/http"
"go.uber.org/dig"
)
// Each handler contributes one route to the "routes" group.
type RouteResult struct {
dig.Out
Route Route `group:"routes"`
}
type Route struct {
Pattern string
Handler http.Handler
}
func NewHealthRoute() RouteResult {
return RouteResult{Route: Route{
Pattern: "/health",
Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}),
}}
}
func NewUserRoute(repo *UserRepo) RouteResult {
return RouteResult{Route: Route{
Pattern: "/users",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
users, err := repo.List(r.Context())
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%d users", len(users))
}),
}}
}
// The server consumes every Route registered to "routes".
type ServerParams struct {
dig.In
Routes []Route `group:"routes"`
}
func NewServer(p ServerParams) *http.Server {
mux := http.NewServeMux()
for _, r := range p.Routes {
mux.Handle(r.Pattern, r.Handler)
}
return &http.Server{Addr: ":8080", Handler: mux}
}
func main() {
c := dig.New()
must(c.Provide(NewDB)) // *sql.DB
must(c.Provide(NewUserRepo)) // *UserRepo
must(c.Provide(NewHealthRoute)) // adds to group
must(c.Provide(NewUserRoute)) // adds to group
must(c.Provide(NewServer))
err := c.Invoke(func(srv *http.Server) error {
log.Println("listening on", srv.Addr)
return srv.ListenAndServe()
})
if err != nil {
log.Fatal(err)
}
}
func must(err error) {
if err != nil {
panic(err)
}
}Two databases (read-write + read-only)
type DBResult struct {
dig.Out
Primary *sql.DB `name:"primary"`
ReadOnly *sql.DB `name:"readonly"`
}
func NewDatabases(cfg *Config) (DBResult, error) {
rw, err := sql.Open("postgres", cfg.PrimaryDSN)
if err != nil {
return DBResult{}, fmt.Errorf("primary: %w", err)
}
ro, err := sql.Open("postgres", cfg.ReadOnlyDSN)
if err != nil {
rw.Close()
return DBResult{}, fmt.Errorf("readonly: %w", err)
}
return DBResult{Primary: rw, ReadOnly: ro}, nil
}
type RepoParams struct {
dig.In
Writer *sql.DB `name:"primary"`
Reader *sql.DB `name:"readonly"`
}
func NewUserRepo(p RepoParams) *UserRepo {
return &UserRepo{w: p.Writer, r: p.Reader}
}Provide as interface (dig.As) to hide concrete types
type Cache interface {
Get(key string) (string, bool)
Set(key, value string)
}
type RedisCache struct {
client *redis.Client
metrics *Metrics // an internal field consumers should not see
}
func NewRedisCache(client *redis.Client, m *Metrics) *RedisCache {
return &RedisCache{client: client, metrics: m}
}
func (c *RedisCache) Get(key string) (string, bool) { /* ... */ }
func (c *RedisCache) Set(key, value string) { /* ... */ }
func main() {
c := dig.New()
must(c.Provide(NewRedisClient))
must(c.Provide(NewMetrics))
// Consumers see Cache, never *RedisCache or its internals.
must(c.Provide(NewRedisCache, dig.As(new(Cache))))
must(c.Invoke(func(cache Cache) {
cache.Set("hello", "world")
}))
}Request-scoped dependencies
A child scope inherits its parent's providers but adds request-local ones:
root := dig.New()
must(root.Provide(NewLogger))
must(root.Provide(NewDB))
must(root.Provide(NewHandler)) // *Handler is shared; the scope inherits it
func handle(w http.ResponseWriter, req *http.Request) {
scope := root.Scope("request")
// Request-scoped values
must(scope.Provide(func() *http.Request { return req }))
must(scope.Provide(func() RequestID { return RequestID(req.Header.Get("X-Request-ID")) }))
must(scope.Decorate(func(l *zap.Logger) *zap.Logger {
return l.With(zap.String("request_id", req.Header.Get("X-Request-ID")))
}))
err := scope.Invoke(func(h *Handler) error {
return h.Serve(w, req)
})
if err != nil {
http.Error(w, err.Error(), 500)
}
}The decorator only applies inside the request scope — sibling scopes (other in-flight requests) keep their own logger.
Optional dependency for graceful degradation
type WorkerParams struct {
dig.In
DB *sql.DB
Tracer trace.Tracer `optional:"true"` // app still boots without OTel
}
func NewWorker(p WorkerParams) *Worker {
w := &Worker{db: p.DB}
if p.Tracer != nil {
w.tracer = p.Tracer
} else {
w.tracer = trace.NewNoopTracerProvider().Tracer("noop")
}
return w
}Reach for optional only when the dependency is genuinely optional — a missing DB hidden behind optional becomes a nil-pointer panic at first use.
Decorate to add cross-cutting behavior
// Wrap the *sql.DB with a metrics-recording wrapper everywhere.
must(c.Decorate(func(db *sql.DB, m *Metrics) *sql.DB {
return wrapWithMetrics(db, m)
}))
// Wrap the logger with service tags.
must(c.Decorate(func(log *zap.Logger, cfg *Config) *zap.Logger {
return log.With(
zap.String("service", cfg.ServiceName),
zap.String("env", cfg.Env),
)
}))Decorators are scope-local. A decorator on the root applies everywhere; a decorator on a child scope only applies to that subtree.
DryRun for graph validation in tests
func TestWiringIsValid(t *testing.T) {
c := dig.New(dig.DryRun(true))
// Register everything main() registers
must := func(err error) {
require.NoError(t, err)
}
must(c.Provide(NewConfig))
must(c.Provide(NewLogger))
must(c.Provide(NewDB))
must(c.Provide(NewServer))
// Invoke the composition root: dig validates types without running constructors.
require.NoError(t, c.Invoke(func(*http.Server) {}))
}This catches "no provider for *X" failures at build time instead of in production.
Visualizing a failed graph
err := c.Invoke(run)
if err != nil {
f, _ := os.Create("graph.dot")
defer f.Close()
_ = dig.Visualize(c, f, dig.VisualizeError(err))
log.Fatalf("wiring failed (graph in graph.dot): %v", err)
}
// Render: dot -Tpng graph.dot -o graph.pngVisualizeError highlights the missing edges in red — much faster than reading the wrapped error chain.
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-uber-dig · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-uber-dig.zip