Skip to content
Development
Skill

/golang-dependency-injection

Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this

From plugin
cc-skills-golang
3.8k46 skills

Claude Code

$ npx -y skills add samber/cc-skills-golang --skill golang-dependency-injection --agent claude-code

SKILL.md

golang-dependency-injection.SKILL.md
name: golang-dependency-injection
description: "Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go. For a specific DI library, โ†’ See `samber/cc-skills-golang@golang-google-wire`, `samber/cc-skills-golang@golang-uber-dig`, `samber/cc-skills-golang@golang-uber-fx`, or `samber/cc-skills-golang@golang-samber-do` skills."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.3.1"
  openclaw:
    emoji: "๐Ÿ”Œ"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
    install: []
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 AskUserQuestion
paths:
  - "**/*.go"

**Persona:** You are a Go software architect. You guide teams toward testable, loosely coupled designs โ€” you choose the simplest DI approach that solves the problem, and you never over-engineer.

**Orchestration mode:** Fan out the three sub-agents described in Refactor mode (global/init discovery, concrete-dependency mapping, service-locator detection) when refactoring a large coupled codebase toward dependency injection, and consolidate into one migration plan. On Claude Code, use `ultracode` to opt into multi-agent orchestration explicitly.

**Modes:**

  • **Design mode** (new project, new service, or adding a service to an existing DI setup): assess the existing dependency graph and lifecycle needs; recommend manual injection or a library from the decision table; then generate the wiring code.
  • **Refactor mode** (existing coupled code): use up to 3 parallel sub-agents โ€” Agent 1 identifies global variables and `init()` service setup, Agent 2 maps concrete type dependencies that should become interfaces, Agent 3 locates service-locator anti-patterns (container passed as argument) โ€” then consolidate findings and propose a migration plan.

> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-dependency-injection` skill takes precedence.

Dependency Injection in Go

Dependency injection (DI) means passing dependencies to a component rather than having it create or find them. In Go, this is how you build testable, loosely coupled applications โ€” your services declare what they need, and the caller (or container) provides it.

This skill is not exhaustive. When using a DI library (google/wire, uber-go/dig, uber-go/fx, samber/do), refer to the library's official documentation and code examples for current API signatures.

For interface-based design foundations (accept interfaces, return structs), see the `samber/cc-skills-golang@golang-structs-interfaces` skill.

Best Practices Summary

1. Dependencies MUST be injected via constructors โ€” NEVER use global variables or `init()` for service setup 2. Small projects (< 10 services) SHOULD use manual constructor injection โ€” no library needed 3. Interfaces MUST be defined where consumed, not where implemented โ€” accept interfaces, return structs 4. NEVER use global registries or package-level service locators 5. The DI container MUST only exist at the composition root (`main()` or app startup) โ€” NEVER pass the container as a dependency 6. **Prefer lazy initialization** โ€” only create services when first requested 7. **Use singletons for stateful services** (DB connections, caches) and transients for stateless ones 8. **Mock at the interface boundary** โ€” DI makes this trivial 9. **Keep the dependency graph shallow** โ€” deep chains signal design problems 10. **Choose the right DI library** for your project size and team โ€” see the decision table below

Why Dependency Injection?

| Problem without DI | How DI solves it | | --- | --- | | Functions create their own dependencies | Dependencies are injected โ€” swap implementations freely | | Testing requires real databases, APIs | Pass mock implementations in tests | | Changing one component breaks others | Loose coupling via interfaces โ€” components don't know each other's internals | | Services initialized everywhere | Centralized container manages lifecycle (singleton, factory, lazy) | | All services loaded at startup | Lazy loading โ€” services created only when first requested | | Global state and `init()` functions | Explicit wiring at startup โ€” predictable, debuggable |

DI shines in applications with many interconnected services โ€” HTTP servers, microservices, CLI tools with plugins. For a small script with 2-3 functions, manual wiring is fine. Don't over-engineer.

Manual Constructor Injection (No Library)

For small projects, pass dependencies through constructors. See [Manual DI examples](./references/manual-di.md) for a complete application example.

// โœ“ Good โ€” explicit dependencies, testable
type UserService struct {
    db     UserStore
    mailer Mailer
    logger *slog.Logger
}

func NewUserService(db UserStore, mailer Mailer, logger *slog.Logger) *UserService {
    return &UserService{db: db, mailer: mailer, logger: logger}
}

// main.go โ€” manual wiring
func main() {
    logger := slog.Default()
    db := postgres.NewUserStore(connStr)
    mailer := smtp.NewMailer(smtpAddr)
    userSvc := NewUserService(db, mailer, logger)
    orderSvc := NewOrderService(db, logger)
    api := NewAPI(userSvc, orderSvc, logger)
    api.ListenAndServe(":8080")
}
// โœ— Bad โ€” hardcoded dependencies, untestable
type UserService struct {
    db *sql.DB
Read more
@samber
Ships withcc-skills-golang

AI agent skills are reusable instruction sets that extend your coding assistant with domain-specific expertise, loaded on demand so they don't bloat your context. This repository covers Go-specific skills only (language, testing, security, observability, etc.)

Stars on GitHub

Momentum

stars in total
3.8k
Star history of samber/cc-skills-golang on GitHub, a chart by star-history.com

Other skills on cc-skills-golang.

golang-benchmark

golang-benchmark

Golang benchmarking, profiling, and performance measurement. Use when writing, running, or comparing Go benchmarks, profiling hotโ€ฆ

golang-cli

golang-cli

Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool โ€” especially for command structure,โ€ฆ

golang-code-style

golang-code-style

Golang code style conventions โ€” line length and breaking, variable declarations, control flow clarity, when comments help vsโ€ฆ

golang-concurrency

golang-concurrency

Golang concurrency design โ€” goroutine lifecycle and leak prevention, channels and `select`, channel ownership and direction,โ€ฆ

golang-context

golang-context

Idiomatic context.Context usage in Golang โ€” propagation through API boundaries, cancellation, timeouts and deadlines,โ€ฆ

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, orโ€ฆ

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills11d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android โ€” semantic ARIA roles and labels,โ€ฆ

ecc13d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commitsโ€ฆ

react2d252k
@facebook@facebookInstall Skill

Questions about golang-dependency-injection.

Which coding agents can use golang-dependency-injection?
golang-dependency-injection installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.