К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

golang-uber-dig — скилл для Claude Code: настройка DI

Скилл помогает собрать граф зависимостей Go-приложения с помощью uber-go/dig. Пригодится, когда нужно связать конструкторы и зависимости на старте приложения.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add samber/cc-skills-golang --skill golang-uber-dig -a claude-code
Открыть на GitHub

Что делает golang-uber-dig

Скилл разбирает контейнер dig и его основные операции: Provide регистрирует конструкторы, а Invoke запрашивает нужные зависимости. Конструкторы запускаются при первом запросе результата, а созданные значения повторно используются внутри контейнера. Ошибка конструктора возвращается вместе с путём зависимостей, который к ней привёл.

Для нескольких зависимостей скилл показывает dig.In, а для нескольких результатов одного конструктора — dig.Out. Теги позволяют задавать именованные зависимости, необязательные поля и группы значений; порядок элементов группы не гарантирован. Для регистрации типа под интерфейсом есть dig.As.

Это скилл для Go-проектов с go.uber.org/dig; в разрешённых инструментах есть go. У dig нет встроенного управления жизненным циклом: если приложению нужны хуки запуска и остановки, обработка сигналов и штатное завершение, в тексте предлагается fx.

Какие задачи решает

  • связать конструкторы в граф зависимостей
  • сгруппировать зависимости конструктора через dig.In
  • вернуть несколько именованных результатов через dig.Out
  • собрать значения из группы в срез
  • проверить ошибки при разрешении зависимостей

Примеры запросов агенту

  • Разбери граф зависимостей в Go-проекте с `go.uber.org/dig` и покажи, где использовать `Provide` и `Invoke`.
  • Сгруппируй параметры этого конструктора через `dig.In`, включая именованные и необязательные зависимости.
  • Проверь, как собрать несколько реализаций `http.Handler` в группу `routes` и передать их серверу.

Как установить golang-uber-dig

1Через Skills CLI (Vercel)

npx skills add samber/cc-skills-golang --skill golang-uber-dig -a claude-code

2Вручную: положить файлы

~/.claude/skills/golang-uber-dig/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/golang-uber-dig/

Из того же набора38

Весь набор →
golang-code-style samber Скилл помогает писать понятный код на Go, разбирая правила длины строк, объявления переменных, управления потоком выполнения и комментариев. Пригодится при написании и ревью кода, обсуждении стилистики или установке стандартов проекта. Claude Code CX Codex Cursor +1 44 000установок golang-error-handling samber Скилл для идиоматичной обработки ошибок в Go: оборачивание с контекстом, проверка цепочек, структурированное логирование и интеграция с samber/oops. Применяется при создании, оборачивании, инспекции и логировании ошибок. Claude Code CX Codex Cursor +1 43 200установок golang-security samber Находит уязвимости в коде на Go, выстраивает аудит по STRIDE и DREAD и помогает закрывать инъекции, утечки секретов и ошибки в криптографии. Claude Code CX Codex Cursor +1 42 100установок golang-design-patterns samber Скилл подсказывает идиоматичные Go-паттерны для API, жизненного цикла ресурсов, graceful shutdown и архитектуры. Пригодится при проектировании и ревью кода. Claude Code CX Codex Cursor +1 41 900установок golang-performance samber Помогает находить и устранять узкие места в Go-коде: сокращает аллокации памяти, оптимизирует горячие циклы и проверяет результаты замеров. Claude Code CX Codex Cursor +1 41 800установок golang-concurrency samber Скилл задаёт правила для конкурентного кода на Go: жизненный цикл горутин, каналы и select, мьютексы, errgroup, singleflight, воркер-пулы и fan-out/fan-in пайплайны. Claude Code CX Codex Cursor +1 41 600установок golang-database samber Набор правил для работы с реляционными базами данных в Go через database/sql, sqlx и pgx. Помогает писать запросы без ORM и проверять утечки соединений. Claude Code CX Codex Cursor +1 40 700установок golang-naming samber Скилл задаёт правила имён в Go: пакеты, типы, ошибки, булевы поля и тесты. Пригодится при написании, ревью и рефакторинге кода. Claude Code CX Codex Cursor +1 40 700установок

Похожие

iii-sdk-reference iii-hq Справка по API iii SDK для Node.js, Python, Rust, Go и браузера. Помогает быстро найти правильный синтаксис регистрации воркеров, функций, триггеров, наблюдателей и каналов на нужном языке. Claude Code CX Codex Cursor +1 4 000установок python-packaging Seth Hobson Скилл помогает собрать Python-библиотеку или CLI-инструмент в устанавливаемый пакет и подготовить публикацию в PyPI. Подходит для настройки структуры проекта. Claude Code CX Codex Cursor 12 915установок php-pro https://github.com/Jeffallan Задаёт правила разработки на PHP 8.3+ для Laravel и Symfony: включает strict_types, анализ в PHPStan на уровне 9 и тесты PHPUnit или Pest. Claude Code CX Codex Cursor +1 15 500установок python-type-safety Seth Hobson Помогает добавлять типы в Python-код, писать дженерики и протоколы, а также настраивать строгую проверку через mypy или pyright. Claude Code CX Codex Cursor 12 643установок migrate-to-shoehorn Matt Pocock Переводит type assertions с as в тестах на функции из @total-typescript/shoehorn. Нужен для частичных объектов и намеренно неверных данных в проверках. Claude Code 475 388установок write-swift emilkowalski Скилл помогает писать, проверять и переносить код на Swift с учётом модели языка. Подойдёт, когда нужно разобраться с конкурентностью, ошибкой или циклом удержания объектов. Claude Code CX Codex Cursor +1 117 500установок megacave JuliusBrussee Переводит ответы ассистента на классический китайский язык (вэньянь) для экономии места на экране. Активируется командами /megacave или /caveman wenyan. Claude Code CX Codex Cursor +1 24 400установок find-docs upstash Тянет актуальную документацию, справочники API и примеры кода для любой библиотеки через Context7 CLI. Пригодится, когда агент отвечает по устаревшим данным обучения. Claude Code CX Codex Cursor +1 9 400установок

Вопросы о golang-uber-dig

Как установить golang-uber-dig в Claude Code?

Выполните npx skills add samber/cc-skills-golang --skill golang-uber-dig -a claude-code. Скилл появится в ~/.claude/skills/golang-uber-dig/SKILL.md.

Что делает golang-uber-dig?

Он помогает использовать uber-go/dig для связывания конструкторов и зависимостей в Go-приложении: от регистрации через Provide до получения объектов через Invoke.

Чем `dig` отличается от `fx`?

dig отвечает за граф зависимостей, а fx добавляет управление жизненным циклом, обработку сигналов и модули. Для приложения с хуками запуска и остановки скилл советует рассмотреть fx.

Исходный текст

SKILL.md · MIT
---
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, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.2.2"
  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 Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**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:**

- [pkg.go.dev/go.uber.org/dig](https://pkg.go.dev/go.uber.org/dig)
- [github.com/uber-go/dig](https://github.com/uber-go/dig)

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-dev` skill (`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-gopls` skill (`gopls`).
- Context7 remains a fallback for docs not indexed on pkg.go.dev.

```bash
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

```go
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

```go
// 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:

```go
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:

```go
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`:

```go
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:

```go
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:

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

## Full Application Example

```go
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](./references/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

| 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](./references/testing.md).

## Further Reading

- [advanced.md](./references/advanced.md) — Decorate, Scopes, optional deps, error helpers, Visualize, full Quick Reference
- [recipes.md](./references/recipes.md) — end-to-end examples: HTTP server with route group, two databases, request scopes, decorators, dry-run validation
- [testing.md](./references/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>.

© samber · MIT · samber/cc-skills-golang

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой