[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DFEXZK687ER1E1KKTM84G7":3,"skill-same:01M7DFEXZK687ER1E1KKTM84G7":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},"01M7DFEXZK687ER1E1KKTM84G7","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.","heynemann\u002Fomp-marketplace","heynemann","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F60965?v=4","01M7DFBD9ZDB2J2QE7R4AR0PES","Bernardo Heynemann","01M7DFBDAM3NXF540P210W3NYT",0,"MIT","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\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","2147d79c9cd764770418b462c29634bcdc710096","plugins\u002Fbase\u002Fskills\u002Fgolang-dependency-injection","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace","https:\u002F\u002Fgithub.com\u002Fheynemann","http:\u002F\u002Fwww.thumbor.org","CTO @ Flutter Brazil | Former Meta & Coinbase","2026-09-29 21:26:05",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":38},[49,52,55],{"tool":50,"command":51},"npx","npx skills add heynemann\u002Fomp-marketplace --skill golang-dependency-injection",{"tool":53,"command":54},"bunx","bunx skills add heynemann\u002Fomp-marketplace --skill golang-dependency-injection",{"tool":56,"command":57},"pnpm","pnpm dlx skills add heynemann\u002Fomp-marketplace --skill golang-dependency-injection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\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\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\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\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\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\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\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\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\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\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fgolang-dependency-injection\u002Freferences\u002Fuber-dig-fx.md",[83,90,97,104,111,118],{"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":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7DFXDYP0N6P8KR0AF7C0TDK","writing-for-agents","Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md.","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fwriting-for-agents\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7DFX9C5B0T1T0AVDCWNR5P2","write-skill","Use when creating, designing, or fixing an agent skill (SKILL.md pack) — triggers include \"write a skill\", \"make me a skill\", \"create a skill\", skill directories, and skills that fail to trigger or fire on the wrong tasks.","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fwrite-skill\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7DFX64VSTQV0CSGYR76MPZF","write-agent","Use when creating, designing, or fixing an omp subagent (task agent) — triggers include \"write an agent\", \"make me an agent\", \"create a subagent\", agent `.md` definitions, and agents that misbehave when spawned via task.","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fwrite-agent\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7DFX22JEY7ZN9EDESM732K5","wizard","Generate an interactive bash wizard that walks a human through steps only they can perform. Use when provisioning infrastructure, setting up credentials or CI secrets, walking an unfamiliar third-party dashboard, or running a one-off migration or cutover. Don't invoke this for steps the agent can perform itself.","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fwizard\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M7DFWYXR5V2CY2BPDAAS19R1","wayfinder","Plan a huge chunk of work (more than one agent session can hold) as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear.","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fwayfinder\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":19},"01M7DFWXFFMBKV294WS66S475V","wait-what","Stop. That last message did not land: re-pitch it.","https:\u002F\u002Fgithub.com\u002Fheynemann\u002Fomp-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fbase\u002Fskills\u002Fwait-what\u002FSKILL.md",[],[]]