[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76H5XCAC5X5WJYR7DH1T4B7":3,"skill-same:01M76H5XCAC5X5WJYR7DH1T4B7":68},{"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":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":44,"ownerHtmlUrl":45,"ownerBlogUrl":46,"ownerDescription":47,"updatedAt":48,"install":49,"resources":61},"01M76H5XCAC5X5WJYR7DH1T4B7","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.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fgolang-dependency-injection\u002FSKILL.md",[],[],"2026-11-12 13:55:43",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,"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fmarketplace\u002Fgolang-dependency-injection",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":38},[51,54,57],{"tool":52,"command":53},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill golang-dependency-injection",{"tool":55,"command":56},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill golang-dependency-injection",{"tool":58,"command":59},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill golang-dependency-injection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fgolang-dependency-injection\u002FSKILL.md",[62],{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},"skill-report.json","REFERENCE","参考文档",41687,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fgolang-dependency-injection\u002Fskill-report.json",[69,77,84,91,98,105],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":76},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":76},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":76},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\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":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":76},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\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":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":76},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\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":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":76},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]