golang-dependency-injection
Comprehensive guide for dependency injection (DI) in Golang.
Skill by samber
Chalk Labs
Need help deploying golang-dependency-injection?
Chalk Labs sets up agents like this inside real teams: connected to your tools, tested on your data, with a human in the loop where it matters.
Install
Works with Claude Code. Read the repository before you give any tool access to your data.
npx agentmarket install skill/paulohgodinho-golang-dependency-injection
Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
Permissions
What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.
- Tools
- No tools found
- Secrets
- None asked for
- Install scripts
- None found
Network hosts it talks to 1
codeload.github.com· found in install command
Files it touches
~/.claude/skills/golang-dependency-injection
Tools it pre-approves 12
From allowed-tools in SKILL.md: the agent may use these without asking you each time.
ReadEditWriteGlobGrepBash(go:*)Bash(golangci-lint:*)Bash(git:*)AgentWebFetchmcp__context7__resolve-library-idmcp__context7__query-docs
What's inside
- Skill 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). 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.
- License
- MIT
- Compatibility
- Designed for Claude Code or similar AI coding agents, and for projects using Golang.
- 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
- Metadata
- author: samber · version: 1.0
- Instructions
- 221 lines in SKILL.md · view on GitHub
Before installing
- Pre-approves some shell commands
Files (5)
- SKILL.md
- evals.json · evals/
- google-wire.md · references/
- manual-di.md · references/
- uber-dig-fx.md · references/
SKILL.md (first lines)
**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.
**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), 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.
```go
// ✓ 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")
}
```
```go
// ✗ Bad — hardcoded dependencies, untestable
type UserService struct {
db *sql.DB
}
func NewUserService() *UserService {
db, _ := sql.Open("postgres", os.Getenv("DATABASE_URL")) // hidden dependency
return &UserService{db: db}
}
```
Manual DI breaks down when:
- You have 15+ services with cross-dependencies
- You need lifecycle management (health checks, graceful shutdown)
- You want lazy initialization or scoped containers
- Wiring order becomes fragile and hard to maintain
## DI Library Comparison
Go has two main approaches to DI libraries:
- [google/wire examples](./references/google-wire.md) — Compile-time code generation
- [uber-go/dig + fx examples](./references/uber-dig-fx.md) — Reflection-based framework
### Decision Table
| Criteria | Manual | google/wire | uber-go/dig + fx |
| --- | --- | --- | --- |
| **Project size** | Small (< 10 services) | Medium-Large | Large |
| **Type safety** | Compile-time | Compile-time (codegen) | Runtime (reflection) |
| **Code generation** | None | Required (`wire_gen.go`) | None |
| **Reflection** | None | None | Yes |
| **API style** | N/A | Provider sets + build tags | Struct tags + decorators |
| **Lazy loading** | Manual | N/A (all eager) | Built-in (fx) |
| **Singletons** | Manual | Built-in | Built-in |
| **Transient/factory** | Manual | Manual | Built-in |
| **Scopes/modules** | Manual | Provider sets | Module system (fx) |
| **Health checks** | Manual | Manual | Manual |
| **Graceful shutdown** | Manual | Manual | Built-in (fx) |
| **Debugging** | Print statements | Compile errors | `fx.Visualize()` |
| **Go version** | Any | Any | Any |
| **Learning curve** | None | Medium | High |
### Quick Comparison: Same App, Four Ways
The dependency graph: `Config -> Database -> UserStore -> UserService -> API`From paulohgodinho/skills, MIT.
More from paulohgodinho/skills
- 0.414score
golang-naming
samber
Go (Golang) naming conventions — covers packages, constructors, structs, interfaces, constants, enums, errors, booleans, receivers, getters/setters…
SkillDFreshness: DClaude Code +9 - 0.414score
golang-project-layout
samber
Provides a guide for setting up Golang project layouts and workspaces.
SkillDFreshness: DClaude Code +9 - 0.414score
golang-code-style
samber
Golang code style, formatting and conventions.
SkillDFreshness: DClaude Code +9 - 0.414score
golang-design-patterns
samber
Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown…
SkillDFreshness: DClaude Code +9 - 0.410score
golang-lint
samber
Provides linting best practices and golangci-lint configuration for Go projects.
SkillDFreshness: DClaude Code +9 - 0.409score
golang-structs-interfaces
samber
Golang struct and interface design patterns — composition, embedding, type assertions, type switches, interface segregation, dependency injection via…
SkillDFreshness: DClaude Code +9 - 0.409score
golang-cli
samber
Golang CLI application development.
SkillDFreshness: DClaude Code +9 - 0.409score
golang-build
samber
Cross-platform build script for Go projects using a build.go file at the repository root.
SkillDFreshness: DClaude Code +9
Signals
- Stars
- 0
- Forks
- 0
- Open issues
- 0
- Last commit (this folder)
- Apr 4, 2026 (7 months ago)
From GitHub (fetched Oct 24, 2026).
Details
- Version
- 1.0
- License
- MIT
- Repository
- github.com/paulohgodinho/skills
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from samber
- 0.563score
golang-design-patterns
samber
Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown…
SkillBFreshness: B★ 2Claude Code +9 - 0.563score
golang-performance
samber
Golang performance optimization patterns and methodology - if X bottleneck, then apply Y.
SkillBFreshness: B★ 2Claude Code - 0.563score
golang-security
samber
Security best practices and vulnerability prevention for Golang.
SkillBFreshness: B★ 2Claude Code - 0.563score
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak…
SkillBFreshness: B★ 2Claude Code +9 - 0.563score
golang-documentation
samber
Comprehensive documentation guide for Golang projects, covering godoc comments, README, CONTRIBUTING, CHANGELOG, Go Playground, Example tests, API docs, and…
SkillBFreshness: B★ 2Claude Code - 0.534score
golang-concurrency
samber
Golang concurrency patterns.
SkillCFreshness: C★ 5Claude Code +9
Done for you
Rather not set it up yourself?
Chalk Labs scopes, builds and runs agents for your team: the task audit, the eval harness, the integrations and the weekly ops report. Fixed scope, priced before we start.
See how we build AI agents →Read the case studies
Chalk Labs is a two-founder AI and growth studio. We build AI agents, CRMs and MVPs for Web3 and AI companies, and have shipped 50+ product and token launches.
- launches shipped
- 50+
- launches shipped
- media placements
- 500+
- media placements
- founders on every account
- 2
- founders on every account
Press we've placed: Forbes · CoinDesk · Decrypt · Cointelegraph · The Block
Rahil Jain, Co-founder, Chalk Labs. Ex-Goldman Sachs engineer. You talk to the person who builds it.
Get golang-dependency-injection running in your business
Tell us what you want to automate. A founder replies within one working day with a plan, not a pitch deck.
Cite this page
golang-dependency-injection skill. Agent Mart. https://agentmart.dev/skills/paulohgodinho-golang-dependency-injection (last updated 2026-10-24)