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://mp-staging.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/advanced.md
Advanced — uber-go/dig
Detail topics that are referenced from SKILL.md. Each section is self-contained.
Table of Contents
Decorate
Scopes
Optional Dependencies
Error Handling
Visualization
Quick Reference
Container
Provide options
Container options
Errors
Decorate
Decorate modifies a value already provided in the container — the decorator receives the original instance and returns a replacement. Common uses: enriching a logger with context, wrapping a metrics scope with tags, swapping a real client for a recording one in a child scope.
c.Decorate(func(log *zap.Logger) *zap.Logger {
return log.Named("worker")
})Decorators apply to the scope they were registered in and to that scope's descendants. Use them at scope boundaries or package wiring boundaries, not in main(), so changes stay local.
Scopes
A Scope is a child container that inherits providers from its parent and can add or override its own. Scopes let request-, tenant-, or module-level dependencies coexist with shared singletons:
root := dig.New()
root.Provide(NewLogger)
root.Provide(NewDatabase)
requestScope := root.Scope("request")
requestScope.Provide(NewRequestContext) // only visible inside requestScope
requestScope.Decorate(func(l *zap.Logger) *zap.Logger {
return l.With(zap.String("scope", "request"))
})By default, providers registered to a scope are private to that scope and its children. Pass dig.Export(true) to Provide inside a scope to make the type visible from the parent:
requestScope.Provide(NewSharedCache, dig.Export(true))Optional Dependencies
optional:"true" lets a consumer compile and run when a provider is missing. Use it sparingly — optional dependencies hide configuration mistakes. They make sense for genuinely optional features (a tracing exporter, an in-memory cache) but not for core services like a database.
type Params struct {
dig.In
Logger *zap.Logger
Tracer trace.Tracer `optional:"true"`
}Error Handling
dig wraps the constructor error with the dependency path so you can see which graph edge failed:
if err := c.Invoke(run); err != nil {
// err describes the chain: "could not build *http.Server: ..."
}Useful helpers:
errors.As(err, &dig.Error{})— true if the error originated inside digdig.RootCause(err)— unwrap to the original constructor error returned by user codedig.IsCycleDetected(err)— true if the graph contains a cycle (typically reported at firstInvokeunlessDeferAcyclicVerificationis set)errors.As(err, &dig.PanicError{})— whenRecoverFromPanicsis enabled, a panicking constructor surfaces as this typed error
Visualization
dig can emit the dependency graph in DOT format — useful when wiring becomes too tangled to reason about by reading code:
f, _ := os.Create("graph.dot")
_ = dig.Visualize(c, f)
// then: dot -Tpng graph.dot -o graph.pngdig.VisualizeError(err) highlights the failed edges when an Invoke returns an error — invaluable for debugging "missing type" failures in deep graphs.
Quick Reference
Container
| Function/Method | Purpose |
|---|---|
dig.New(opts...) | Create a root container |
c.Provide(ctor, opts...) | Register a constructor |
c.Invoke(fn, opts...) | Run a function with injected dependencies |
c.Decorate(fn, opts...) | Modify a previously-provided value within a scope |
c.Scope(name, opts...) | Create a child scope (private providers by default) |
c.String() | Human-readable text summary of providers (not DOT; use dig.Visualize for DOT) |
Provide options
| Option | Purpose |
|---|---|
dig.Name("...") | Disambiguate same-typed providers |
dig.Group("...") | Add the result to a value group |
dig.As(new(I)) | Provide the concrete value as one or more interfaces |
dig.Export(true) | Make a scope-level provider visible from the root |
dig.FillProvideInfo(&info) | Capture metadata for tooling |
Container options
| Option | Purpose |
|---|---|
dig.DeferAcyclicVerification() | Defer cycle check to first Invoke |
dig.RecoverFromPanics() | Convert constructor panics into dig.PanicError |
dig.DryRun(true) | Validate without invoking constructors |
Errors
| Helper | Purpose |
|---|---|
dig.RootCause(err) | Unwrap to the user-returned error |
dig.IsCycleDetected(err) | True if the graph has a cycle |
errors.As(err, &dig.PanicError{}) | Detect a recovered panic |
dig.Visualize(c, w, opts...) | Write the graph in DOT format |
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