[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79ZG9X0BVGFHNHFDQWGAMC0":3,"skill-same:01M79ZG9X0BVGFHNHFDQWGAMC0":82},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":14,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":59},"01M79ZG9X0BVGFHNHFDQWGAMC0","golang-dependency-injection",null,"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\u002Fwire, uber-go\u002Fdig, uber-go\u002Ffx, samber\u002Fdo). 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\u002Fcc-skills-golang@golang-google-wire`, `samber\u002Fcc-skills-golang@golang-uber-dig`, `samber\u002Fcc-skills-golang@golang-uber-fx`, or `samber\u002Fcc-skills-golang@golang-samber-do` skills.","kongnakornna\u002Fgolangapi","kongnakornna","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10528904?v=4","01M79Z5JQPPV5CWQHXS235Q9MD","Kongnakorn Jantakun","01M79Z5JRHJJJ6PR2DGQS4P985",0,"MIT","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: golang-dependency-injection\ndescription: \"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\u002Fwire, uber-go\u002Fdig, uber-go\u002Ffx, samber\u002Fdo). 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\u002Fcc-skills-golang@golang-google-wire`, `samber\u002Fcc-skills-golang@golang-uber-dig`, `samber\u002Fcc-skills-golang@golang-uber-fx`, or `samber\u002Fcc-skills-golang@golang-samber-do` skills.\"\nuser-invocable: true\nlicense: MIT\ncompatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.\nmetadata:\n  author: samber\n  version: \"1.3.1\"\n  openclaw:\n    emoji: \"🔌\"\n    homepage: https:\u002F\u002Fgithub.com\u002Fsamber\u002Fcc-skills-golang\n    requires:\n      bins:\n        - go\n    install: []\nallowed-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\npaths:\n  - \"**\u002F*.go\"\n---\n\n**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.\n\n**Orchestration mode:** Fan out the three sub-agents described in Refactor mode (global\u002Finit 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.\n\n**Modes:**\n\n- **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.\n- **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.\n\n> **Community default.** A company skill that explicitly supersedes `samber\u002Fcc-skills-golang@golang-dependency-injection` skill takes precedence.\n\n# Dependency Injection in Go\n\nDependency 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.\n\nThis skill is not exhaustive. When using a DI library (google\u002Fwire, uber-go\u002Fdig, uber-go\u002Ffx, samber\u002Fdo), refer to the library's official documentation and code examples for current API signatures.\n\nFor interface-based design foundations (accept interfaces, return structs), see the `samber\u002Fcc-skills-golang@golang-structs-interfaces` skill.\n\n## Best Practices Summary\n\n1. Dependencies MUST be injected via constructors — NEVER use global variables or `init()` for service setup\n2. Small projects (\u003C 10 services) SHOULD use manual constructor injection — no library needed\n3. Interfaces MUST be defined where consumed, not where implemented — accept interfaces, return structs\n4. NEVER use global registries or package-level service locators\n5. The DI container MUST only exist at the composition root (`main()` or app startup) — NEVER pass the container as a dependency\n6. **Prefer lazy initialization** — only create services when first requested\n7. **Use singletons for stateful services** (DB connections, caches) and transients for stateless ones\n8. **Mock at the interface boundary** — DI makes this trivial\n9. **Keep the dependency graph shallow** — deep chains signal design problems\n10. **Choose the right DI library** for your project size and team — see the decision table below\n\n## Why Dependency Injection?\n\n| Problem without DI | How DI solves it |\n| --- | --- |\n| Functions create their own dependencies | Dependencies are injected — swap implementations freely |\n| Testing requires real databases, APIs | Pass mock implementations in tests |\n| Changing one component breaks others | Loose coupling via interfaces — components don't know each other's internals |\n| Services initialized everywhere | Centralized container manages lifecycle (singleton, factory, lazy) |\n| All services loaded at startup | Lazy loading — services created only when first requested |\n| Global state and `init()` functions | Explicit wiring at startup — predictable, debuggable |\n\nDI 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.\n\n## Manual Constructor Injection (No Library)\n\nFor small projects, pass dependencies through constructors. See [Manual DI examples](.\u002Freferences\u002Fmanual-di.md) for a complete application example.\n\n```go\n\u002F\u002F ✓ Good — explicit dependencies, testable\ntype UserService struct {\n    db     UserStore\n    mailer Mailer\n    logger *slog.Logger\n}\n\nfunc NewUserService(db UserStore, mailer Mailer, logger *slog.Logger) *UserService {\n    return &UserService{db: db, mailer: mailer, logger: logger}\n}\n\n\u002F\u002F main.go — manual wiring\nfunc main() {\n    logger := slog.Default()\n    db := postgres.NewUserStore(connStr)\n    mailer := smtp.NewMailer(smtpAddr)\n    userSvc := NewUserService(db, mailer, logger)\n    orderSvc := NewOrderService(db, logger)\n    api := NewAPI(userSvc, orderSvc, logger)\n    api.ListenAndServe(\":8080\")\n}\n```\n\n```go\n\u002F\u002F ✗ Bad — hardcoded dependencies, untestable\ntype UserService struct {\n    db *sql.DB\n}\n\nfunc NewUserService() *UserService {\n    db, _ := sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\")) \u002F\u002F hidden dependency\n    return &UserService{db: db}\n}\n```\n\nManual DI breaks down when:\n\n- You have 15+ services with cross-dependencies\n- You need lifecycle management (health checks, graceful shutdown)\n- You want lazy initialization or scoped containers\n- Wiring order becomes fragile and hard to maintain\n\n## DI Library Comparison\n\nGo has three main approaches to DI libraries:\n\n- [google\u002Fwire examples](.\u002Freferences\u002Fgoogle-wire.md) — Compile-time code generation\n- [uber-go\u002Fdig + fx examples](.\u002Freferences\u002Fuber-dig-fx.md) — Reflection-based framework\n- [samber\u002Fdo examples](.\u002Freferences\u002Fsamber-do.md) — Generics-based, no code generation\n\n### Decision Table\n\n| Criteria | Manual | google\u002Fwire | uber-go\u002Fdig + fx | samber\u002Fdo |\n| --- | --- | --- | --- | --- |\n| **Project size** | Small (\u003C 10 services) | Medium-Large | Large | Any size |\n| **Type safety** | Compile-time | Compile-time (codegen) | Runtime (reflection) | Compile-time (generics) |\n| **Code generation** | None | Required (`wire_gen.go`) | None | None |\n| **Reflection** | None | None | Yes | None |\n| **API style** | N\u002FA | Provider sets + build tags | Struct tags + decorators | Simple, generic functions |\n| **Lazy loading** | Manual | N\u002FA (all eager) | Built-in (fx) | Built-in |\n| **Singletons** | Manual | Built-in | Built-in | Built-in |\n| **Transient\u002Ffactory** | Manual | Manual | Built-in | Built-in |\n| **Scopes\u002Fmodules** | Manual | Provider sets | Module system (fx) | Built-in (hierarchical) |\n| **Health checks** | Manual | Manual | Manual | Built-in interface |\n| **Graceful shutdown** | Manual | Manual | Built-in (fx) | Built-in interface |\n| **Container cloning** | N\u002FA | N\u002FA | N\u002FA | Built-in |\n| **Debugging** | Print statements | Compile errors | `fx.Visualize()` | `ExplainInjector()`, web interface |\n| **Go version** | Any | Any | Any | 1.18+ (generics) |\n| **Learning curve** | None | Medium | High | Low |\n\n### Quick Comparison: Wiring Style\n\nThe same graph — `Config -> Database -> UserStore -> UserService -> API` — wired by hand and by a container. The contrast is what the wiring code encodes: an ordered call sequence you maintain, versus a set of providers the container orders for you.\n\n```go\n\u002F\u002F Manual — you own the order; adding a dependency means editing every call site downstream\ncfg := NewConfig()\ndb := NewDatabase(cfg)\nstore := NewUserStore(db)\nsvc := NewUserService(store)\napi := NewAPI(svc)\napi.Run()\n\u002F\u002F No shutdown hooks, health checks, or lazy loading — add them yourself\n\n\u002F\u002F Container (samber\u002Fdo) — order is derived from the constructor signatures\ni := do.New()\ndo.Provide(i, NewConfig)\ndo.Provide(i, NewDatabase)\ndo.Provide(i, NewUserStore)\ndo.Provide(i, NewUserService)\napi := do.MustInvoke[*API](i)\napi.Run()\ndefer i.Shutdown() \u002F\u002F shutdown and health checks come from the container\n```\n\ngoogle\u002Fwire and uber-go\u002Ffx express the same graph differently: wire generates the manual sequence above at build time from a `wire.Build` provider list (cleanup via `func()` returned by providers, no lifecycle hooks), while fx registers providers with `fx.Provide` and resolves them by reflection at runtime with `OnStart`\u002F`OnStop` hooks. Full wiring examples for each: [google\u002Fwire](.\u002Freferences\u002Fgoogle-wire.md), [uber-go\u002Fdig + fx](.\u002Freferences\u002Fuber-dig-fx.md), [samber\u002Fdo](.\u002Freferences\u002Fsamber-do.md).\n\n## Testing with DI\n\nDI makes testing straightforward — inject mocks instead of real implementations:\n\n```go\n\u002F\u002F Define a mock\ntype MockUserStore struct {\n    users map[string]*User\n}\n\nfunc (m *MockUserStore) FindByID(ctx context.Context, id string) (*User, error) {\n    u, ok := m.users[id]\n    if !ok {\n        return nil, ErrNotFound\n    }\n    return u, nil\n}\n\n\u002F\u002F Test with manual injection\nfunc TestUserService_GetUser(t *testing.T) {\n    mock := &MockUserStore{\n        users: map[string]*User{\"1\": {ID: \"1\", Name: \"Alice\"}},\n    }\n    svc := NewUserService(mock, nil, slog.Default())\n\n    user, err := svc.GetUser(context.Background(), \"1\")\n    if err != nil {\n        t.Fatalf(\"unexpected error: %v\", err)\n    }\n    if user.Name != \"Alice\" {\n        t.Errorf(\"got %q, want %q\", user.Name, \"Alice\")\n    }\n}\n```\n\n### Testing with samber\u002Fdo — Clone and Override\n\nContainer cloning creates an isolated copy where you override only the services you need to mock:\n\n```go\nfunc TestUserService_WithDo(t *testing.T) {\n    \u002F\u002F Create a test injector with mock implementation\n    testInjector := do.New()\n\n    \u002F\u002F Provide the mock UserStore interface\n    do.OverrideValue[UserStore](testInjector, &MockUserStore{\n        users: map[string]*User{\"1\": {ID: \"1\", Name: \"Alice\"}},\n    })\n\n    \u002F\u002F Provide other real services as needed\n    do.Provide[*slog.Logger](testInjector, func(i *do.Injector) (*slog.Logger, error) {\n        return slog.Default(), nil\n    })\n\n    svc := do.MustInvoke[*UserService](testInjector)\n    user, err := svc.GetUser(context.Background(), \"1\")\n    \u002F\u002F ... assertions\n}\n```\n\nThis is particularly useful for integration tests where you want most services to be real but need to mock a specific boundary (database, external API, mailer).\n\n## When to Adopt a DI Library\n\n| Signal | Action |\n| --- | --- |\n| \u003C 10 services, simple dependencies | Stay with manual constructor injection |\n| 10-20 services, some cross-cutting concerns | Consider a DI library |\n| 20+ services, lifecycle management needed | Strongly recommended |\n| Need health checks, graceful shutdown | Use a library with built-in lifecycle support |\n| Team unfamiliar with DI concepts | Start manual, migrate incrementally |\n\n## Common Mistakes\n\n| Mistake | Fix |\n| --- | --- |\n| Global variables as dependencies | Pass through constructors or DI container |\n| `init()` for service setup | Explicit initialization in `main()` or container |\n| Depending on concrete types | Accept interfaces at consumption boundaries |\n| Passing the container everywhere (service locator) | Inject specific dependencies, not the container |\n| Deep dependency chains (A->B->C->D->E) | Flatten — most services should depend on repositories and config directly |\n| Creating a new container per request | One container per application; use scopes for request-level isolation |\n\n## Cross-References\n\n- → See `samber\u002Fcc-skills-golang@golang-samber-do` skill for detailed samber\u002Fdo usage patterns\n- → See `samber\u002Fcc-skills-golang@golang-structs-interfaces` skill for interface design and composition\n- → See `samber\u002Fcc-skills-golang@golang-testing` skill for testing with dependency injection\n- → See `samber\u002Fcc-skills-golang@golang-project-layout` skill for DI initialization placement\n\n## References\n\n- [samber\u002Fdo\u002Fv2 documentation](https:\u002F\u002Fdo.samber.dev) | [github.com\u002Fsamber\u002Fdo\u002Fv2](https:\u002F\u002Fgithub.com\u002Fsamber\u002Fdo)\n- [google\u002Fwire user guide](https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fwire\u002Fblob\u002Fmain\u002Fdocs\u002Fguide.md)\n- [uber-go\u002Ffx documentation](https:\u002F\u002Fuber-go.github.io\u002Ffx\u002F)\n- [uber-go\u002Fdig](https:\u002F\u002Fgithub.com\u002Fuber-go\u002Fdig)\n","**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.\n\n**Orchestration mode:** Fan out the three sub-agents described in Refactor mode (global\u002Finit 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.\n\n**Modes:**\n\n- **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.\n- **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.\n\n> **Community default.** A company skill that explicitly supersedes `samber\u002Fcc-skills-golang@golang-dependency-injection` skill takes precedence.\n\n# Dependency Injection in Go\n\nDependency 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.\n\nThis skill is not exhaustive. When using a DI library (google\u002Fwire, uber-go\u002Fdig, uber-go\u002Ffx, samber\u002Fdo), refer to the library's official documentation and code examples for current API signatures.\n\nFor interface-based design foundations (accept interfaces, return structs), see the `samber\u002Fcc-skills-golang@golang-structs-interfaces` skill.\n\n## Best Practices Summary\n\n1. Dependencies MUST be injected via constructors — NEVER use global variables or `init()` for service setup\n2. Small projects (\u003C 10 services) SHOULD use manual constructor injection — no library needed\n3. Interfaces MUST be defined where consumed, not where implemented — accept interfaces, return structs\n4. NEVER use global registries or package-level service locators\n5. The DI container MUST only exist at the composition root (`main()` or app startup) — NEVER pass the container as a dependency\n6. **Prefer lazy initialization** — only create services when first requested\n7. **Use singletons for stateful services** (DB connections, caches) and transients for stateless ones\n8. **Mock at the interface boundary** — DI makes this trivial\n9. **Keep the dependency graph shallow** — deep chains signal design problems\n10. **Choose the right DI library** for your project size and team — see the decision table below\n\n## Why Dependency Injection?\n\n| Problem without DI | How DI solves it |\n| --- | --- |\n| Functions create their own dependencies | Dependencies are injected — swap implementations freely |\n| Testing requires real databases, APIs | Pass mock implementations in tests |\n| Changing one component breaks others | Loose coupling via interfaces — components don't know each other's internals |\n| Services initialized everywhere | Centralized container manages lifecycle (singleton, factory, lazy) |\n| All services loaded at startup | Lazy loading — services created only when first requested |\n| Global state and `init()` functions | Explicit wiring at startup — predictable, debuggable |\n\nDI 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.\n\n## Manual Constructor Injection (No Library)\n\nFor small projects, pass dependencies through constructors. See [Manual DI examples](.\u002Freferences\u002Fmanual-di.md) for a complete application example.\n\n```go\n\u002F\u002F ✓ Good — explicit dependencies, testable\ntype UserService struct {\n    db     UserStore\n    mailer Mailer\n    logger *slog.Logger\n}\n\nfunc NewUserService(db UserStore, mailer Mailer, logger *slog.Logger) *UserService {\n    return &UserService{db: db, mailer: mailer, logger: logger}\n}\n\n\u002F\u002F main.go — manual wiring\nfunc main() {\n    logger := slog.Default()\n    db := postgres.NewUserStore(connStr)\n    mailer := smtp.NewMailer(smtpAddr)\n    userSvc := NewUserService(db, mailer, logger)\n    orderSvc := NewOrderService(db, logger)\n    api := NewAPI(userSvc, orderSvc, logger)\n    api.ListenAndServe(\":8080\")\n}\n```\n\n```go\n\u002F\u002F ✗ Bad — hardcoded dependencies, untestable\ntype UserService struct {\n    db *sql.DB\n}\n\nfunc NewUserService() *UserService {\n    db, _ := sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\")) \u002F\u002F hidden dependency\n    return &UserService{db: db}\n}\n```\n\nManual DI breaks down when:\n\n- You have 15+ services with cross-dependencies\n- You need lifecycle management (health checks, graceful shutdown)\n- You want lazy initialization or scoped containers\n- Wiring order becomes fragile and hard to maintain\n\n## DI Library Comparison\n\nGo has three main approaches to DI libraries:\n\n- [google\u002Fwire examples](.\u002Freferences\u002Fgoogle-wire.md) — Compile-time code generation\n- [uber-go\u002Fdig + fx examples](.\u002Freferences\u002Fuber-dig-fx.md) — Reflection-based framework\n- [samber\u002Fdo examples](.\u002Freferences\u002Fsamber-do.md) — Generics-based, no code generation\n\n### Decision Table\n\n| Criteria | Manual | google\u002Fwire | uber-go\u002Fdig + fx | samber\u002Fdo |\n| --- | --- | --- | --- | --- |\n| **Project size** | Small (\u003C 10 services) | Medium-Large | Large | Any size |\n| **Type safety** | Compile-time | Compile-time (codegen) | Runtime (reflection) | Compile-time (generics) |\n| **Code generation** | None | Required (`wire_gen.go`) | None | None |\n| **Reflection** | None | None | Yes | None |\n| **API style** | N\u002FA | Provider sets + build tags | Struct tags + decorators | Simple, generic functions |\n| **Lazy loading** | Manual | N\u002FA (all eager) | Built-in (fx) | Built-in |\n| **Singletons** | Manual | Built-in | Built-in | Built-in |\n| **Transient\u002Ffactory** | Manual | Manual | Built-in | Built-in |\n| **Scopes\u002Fmodules** | Manual | Provider sets | Module system (fx) | Built-in (hierarchical) |\n| **Health checks** | Manual | Manual | Manual | Built-in interface |\n| **Graceful shutdown** | Manual | Manual | Built-in (fx) | Built-in interface |\n| **Container cloning** | N\u002FA | N\u002FA | N\u002FA | Built-in |\n| **Debugging** | Print statements | Compile errors | `fx.Visualize()` | `ExplainInjector()`, web interface |\n| **Go version** | Any | Any | Any | 1.18+ (generics) |\n| **Learning curve** | None | Medium | High | Low |\n\n### Quick Comparison: Wiring Style\n\nThe same graph — `Config -> Database -> UserStore -> UserService -> API` — wired by hand and by a container. The contrast is what the wiring code encodes: an ordered call sequence you maintain, versus a set of providers the container orders for you.\n\n```go\n\u002F\u002F Manual — you own the order; adding a dependency means editing every call site downstream\ncfg := NewConfig()\ndb := NewDatabase(cfg)\nstore := NewUserStore(db)\nsvc := NewUserService(store)\napi := NewAPI(svc)\napi.Run()\n\u002F\u002F No shutdown hooks, health checks, or lazy loading — add them yourself\n\n\u002F\u002F Container (samber\u002Fdo) — order is derived from the constructor signatures\ni := do.New()\ndo.Provide(i, NewConfig)\ndo.Provide(i, NewDatabase)\ndo.Provide(i, NewUserStore)\ndo.Provide(i, NewUserService)\napi := do.MustInvoke[*API](i)\napi.Run()\ndefer i.Shutdown() \u002F\u002F shutdown and health checks come from the container\n```\n\ngoogle\u002Fwire and uber-go\u002Ffx express the same graph differently: wire generates the manual sequence above at build time from a `wire.Build` provider list (cleanup via `func()` returned by providers, no lifecycle hooks), while fx registers providers with `fx.Provide` and resolves them by reflection at runtime with `OnStart`\u002F`OnStop` hooks. Full wiring examples for each: [google\u002Fwire](.\u002Freferences\u002Fgoogle-wire.md), [uber-go\u002Fdig + fx](.\u002Freferences\u002Fuber-dig-fx.md), [samber\u002Fdo](.\u002Freferences\u002Fsamber-do.md).\n\n## Testing with DI\n\nDI makes testing straightforward — inject mocks instead of real implementations:\n\n```go\n\u002F\u002F Define a mock\ntype MockUserStore struct {\n    users map[string]*User\n}\n\nfunc (m *MockUserStore) FindByID(ctx context.Context, id string) (*User, error) {\n    u, ok := m.users[id]\n    if !ok {\n        return nil, ErrNotFound\n    }\n    return u, nil\n}\n\n\u002F\u002F Test with manual injection\nfunc TestUserService_GetUser(t *testing.T) {\n    mock := &MockUserStore{\n        users: map[string]*User{\"1\": {ID: \"1\", Name: \"Alice\"}},\n    }\n    svc := NewUserService(mock, nil, slog.Default())\n\n    user, err := svc.GetUser(context.Background(), \"1\")\n    if err != nil {\n        t.Fatalf(\"unexpected error: %v\", err)\n    }\n    if user.Name != \"Alice\" {\n        t.Errorf(\"got %q, want %q\", user.Name, \"Alice\")\n    }\n}\n```\n\n### Testing with samber\u002Fdo — Clone and Override\n\nContainer cloning creates an isolated copy where you override only the services you need to mock:\n\n```go\nfunc TestUserService_WithDo(t *testing.T) {\n    \u002F\u002F Create a test injector with mock implementation\n    testInjector := do.New()\n\n    \u002F\u002F Provide the mock UserStore interface\n    do.OverrideValue[UserStore](testInjector, &MockUserStore{\n        users: map[string]*User{\"1\": {ID: \"1\", Name: \"Alice\"}},\n    })\n\n    \u002F\u002F Provide other real services as needed\n    do.Provide[*slog.Logger](testInjector, func(i *do.Injector) (*slog.Logger, error) {\n        return slog.Default(), nil\n    })\n\n    svc := do.MustInvoke[*UserService](testInjector)\n    user, err := svc.GetUser(context.Background(), \"1\")\n    \u002F\u002F ... assertions\n}\n```\n\nThis is particularly useful for integration tests where you want most services to be real but need to mock a specific boundary (database, external API, mailer).\n\n## When to Adopt a DI Library\n\n| Signal | Action |\n| --- | --- |\n| \u003C 10 services, simple dependencies | Stay with manual constructor injection |\n| 10-20 services, some cross-cutting concerns | Consider a DI library |\n| 20+ services, lifecycle management needed | Strongly recommended |\n| Need health checks, graceful shutdown | Use a library with built-in lifecycle support |\n| Team unfamiliar with DI concepts | Start manual, migrate incrementally |\n\n## Common Mistakes\n\n| Mistake | Fix |\n| --- | --- |\n| Global variables as dependencies | Pass through constructors or DI container |\n| `init()` for service setup | Explicit initialization in `main()` or container |\n| Depending on concrete types | Accept interfaces at consumption boundaries |\n| Passing the container everywhere (service locator) | Inject specific dependencies, not the container |\n| Deep dependency chains (A->B->C->D->E) | Flatten — most services should depend on repositories and config directly |\n| Creating a new container per request | One container per application; use scopes for request-level isolation |\n\n## Cross-References\n\n- → See `samber\u002Fcc-skills-golang@golang-samber-do` skill for detailed samber\u002Fdo usage patterns\n- → See `samber\u002Fcc-skills-golang@golang-structs-interfaces` skill for interface design and composition\n- → See `samber\u002Fcc-skills-golang@golang-testing` skill for testing with dependency injection\n- → See `samber\u002Fcc-skills-golang@golang-project-layout` skill for DI initialization placement\n\n## References\n\n- [samber\u002Fdo\u002Fv2 documentation](https:\u002F\u002Fdo.samber.dev) | [github.com\u002Fsamber\u002Fdo\u002Fv2](https:\u002F\u002Fgithub.com\u002Fsamber\u002Fdo)\n- [google\u002Fwire user guide](https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fwire\u002Fblob\u002Fmain\u002Fdocs\u002Fguide.md)\n- [uber-go\u002Ffx documentation](https:\u002F\u002Fuber-go.github.io\u002Ffx\u002F)\n- [uber-go\u002Fdig](https:\u002F\u002Fgithub.com\u002Fuber-go\u002Fdig)\n",{"name":5,"paths":24,"license":15,"metadata":26,"description":7,"allowed-tools":36,"compatibility":37,"user-invocable":38},[25],"**\u002F*.go",{"author":27,"version":28,"openclaw":29},"samber","1.3.1",{"emoji":30,"install":31,"homepage":32,"requires":33},"🔌",[],"https:\u002F\u002Fgithub.com\u002Fsamber\u002Fcc-skills-golang",{"bins":34},[35],"go","Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs AskUserQuestion","Designed for Claude Code, Codex or similar harness, and for projects using Golang.",true,"main","19f4d52a98d557f3a645a2cfbbeb5bd54f28831d",".github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi","https:\u002F\u002Fgithub.com\u002Fkongnakornna","http:\u002F\u002Fcmoniot.trueddns.com:52160","Technical Skills and Expertise\r\nLanguages and Frameworks\r\nFrontend: HTML, JavaScript, TypeScript, React, Vue, Angular, Next.js\r\nBackend: Node.js,Python,Golang","2026-10-06 23:01:46",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":38},[49,52,55],{"tool":50,"command":51},"npx","npx skills add kongnakornna\u002Fgolangapi --skill golang-dependency-injection",{"tool":53,"command":54},"bunx","bunx skills add kongnakornna\u002Fgolangapi --skill golang-dependency-injection",{"tool":56,"command":57},"pnpm","pnpm dlx skills add kongnakornna\u002Fgolangapi --skill golang-dependency-injection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002FSKILL.md",[60,66,70,74,78],{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"evals\u002Fevals.json","REFERENCE","参考文档",12046,"https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002Fevals\u002Fevals.json",{"path":67,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":68,"sourceHtmlUrl":69},"references\u002Fgoogle-wire.md",2445,"https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002Freferences\u002Fgoogle-wire.md",{"path":71,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Fmanual-di.md",2182,"https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002Freferences\u002Fmanual-di.md",{"path":75,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":76,"sourceHtmlUrl":77},"references\u002Fsamber-do.md",1625,"https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002Freferences\u002Fsamber-do.md",{"path":79,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fuber-dig-fx.md",3909,"https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fgo-cc-skills\u002Fskills\u002Fgolang-dependency-injection\u002Freferences\u002Fuber-dig-fx.md",[83,91,98,105,112,119],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7A0M9RJJ3383VEFYKABWV15","tb-writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftb-writing-plans\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M7A0M4JKY4DEDRP1CBHT00WV","tb-using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftb-using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M7A0KZ5HRAQAAT2KXR6146Q7","tb-test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftb-test-driven-development\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M7A0KW92W3F18E2MRP8H62P2","tb-subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftb-subagent-driven-development\u002FSKILL.md",[],[],{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":19},"01M7A0KKYQCHYYRHA5J5BAP24M","tb-scrutinize","Outsider-perspective end-to-end review of a plan, PR, or code change. First questions intent and whether a simpler\u002Fmore elegant approach would achieve the same goal, then traces the actual code path (not just the diff) to verify the change does what it claims. Output is concise, actionable, and every call carries its rationale. Trigger on \u002Ftb-scrutinize and proactively whenever the user asks to review, audit, sanity-check, or get a second opinion on a plan, PR, diff, design doc, or proposed code change.","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftb-scrutinize\u002FSKILL.md",[],[],{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":87,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":125,"publishedAt":19},"01M7A0KFDR1V3RW7SW1XNHP82P","tb-requesting-code-review","Use when completing tasks, implementing major features, or before merging to verify work meets requirements","https:\u002F\u002Fgithub.com\u002Fkongnakornna\u002Fgolangapi\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftb-requesting-code-review\u002FSKILL.md",[],[]]