skills/golang-dependency-injection/SKILL.md
Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go. For a specific DI library, → See `golang-google-wire`, `golang-uber-dig`, `golang-uber-fx`, or `golang-samber-do` skills.
npx skillsauth add rockcookies/skills golang-dependency-injectionInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Persona: You are a Go software architect. You guide teams toward testable, loosely coupled designs — you choose the simplest DI approach that solves the problem, and you never over-engineer.
Modes:
init() service setup, Agent 2 maps concrete type dependencies that should become interfaces, Agent 3 locates service-locator anti-patterns (container passed as argument) — then consolidate findings and propose a migration plan.Community default. A company skill that explicitly supersedes
golang-dependency-injectionskill takes precedence.
Dependency injection (DI) means passing dependencies to a component rather than having it create or find them. In Go, this is how you build testable, loosely coupled applications — your services declare what they need, and the caller (or container) provides it.
This skill is not exhaustive. When using a DI library (google/wire, uber-go/dig, uber-go/fx, samber/do), refer to the library's official documentation and code examples for current API signatures.
For interface-based design foundations (accept interfaces, return structs), see the golang-structs-interfaces skill.
init() for service setupmain() or app startup) — NEVER pass the container as a dependency| Problem without DI | How DI solves it |
| --- | --- |
| Functions create their own dependencies | Dependencies are injected — swap implementations freely |
| Testing requires real databases, APIs | Pass mock implementations in tests |
| Changing one component breaks others | Loose coupling via interfaces — components don't know each other's internals |
| Services initialized everywhere | Centralized container manages lifecycle (singleton, factory, lazy) |
| All services loaded at startup | Lazy loading — services created only when first requested |
| Global state and init() functions | Explicit wiring at startup — predictable, debuggable |
DI shines in applications with many interconnected services — HTTP servers, microservices, CLI tools with plugins. For a small script with 2-3 functions, manual wiring is fine. Don't over-engineer.
For small projects, pass dependencies through constructors. See Manual DI examples for a complete application example.
// ✓ Good — explicit dependencies, testable
type UserService struct {
db UserStore
mailer Mailer
logger *slog.Logger
}
func NewUserService(db UserStore, mailer Mailer, logger *slog.Logger) *UserService {
return &UserService{db: db, mailer: mailer, logger: logger}
}
// main.go — manual wiring
func main() {
logger := slog.Default()
db := postgres.NewUserStore(connStr)
mailer := smtp.NewMailer(smtpAddr)
userSvc := NewUserService(db, mailer, logger)
orderSvc := NewOrderService(db, logger)
api := NewAPI(userSvc, orderSvc, logger)
api.ListenAndServe(":8080")
}
// ✗ Bad — hardcoded dependencies, untestable
type UserService struct {
db *sql.DB
}
func NewUserService() *UserService {
db, _ := sql.Open("postgres", os.Getenv("DATABASE_URL")) // hidden dependency
return &UserService{db: db}
}
Manual DI breaks down when:
Go has three main approaches to DI libraries:
| Criteria | Manual | google/wire | uber-go/dig + fx | samber/do |
| --- | --- | --- | --- | --- |
| Project size | Small (< 10 services) | Medium-Large | Large | Any size |
| Type safety | Compile-time | Compile-time (codegen) | Runtime (reflection) | Compile-time (generics) |
| Code generation | None | Required (wire_gen.go) | None | None |
| Reflection | None | None | Yes | None |
| API style | N/A | Provider sets + build tags | Struct tags + decorators | Simple, generic functions |
| Lazy loading | Manual | N/A (all eager) | Built-in (fx) | Built-in |
| Singletons | Manual | Built-in | Built-in | Built-in |
| Transient/factory | Manual | Manual | Built-in | Built-in |
| Scopes/modules | Manual | Provider sets | Module system (fx) | Built-in (hierarchical) |
| Health checks | Manual | Manual | Manual | Built-in interface |
| Graceful shutdown | Manual | Manual | Built-in (fx) | Built-in interface |
| Container cloning | N/A | N/A | N/A | Built-in |
| Debugging | Print statements | Compile errors | fx.Visualize() | ExplainInjector(), web interface |
| Go version | Any | Any | Any | 1.18+ (generics) |
| Learning curve | None | Medium | High | Low |
The dependency graph: Config -> Database -> UserStore -> UserService -> API
Manual:
cfg := NewConfig()
db := NewDatabase(cfg)
store := NewUserStore(db)
svc := NewUserService(store)
api := NewAPI(svc)
api.Run()
// No automatic shutdown, health checks, or lazy loading
google/wire:
// wire.go — then run: wire ./...
func InitializeAPI() (*API, error) {
wire.Build(NewConfig, NewDatabase, NewUserStore, NewUserService, NewAPI)
return nil, nil
}
// No lifecycle hooks (OnStart/OnStop) or health checks; cleanup via returned func() from providers
uber-go/fx:
app := fx.New(
fx.Provide(NewConfig, NewDatabase, NewUserStore, NewUserService),
fx.Invoke(func(api *API) { api.Run() }),
)
app.Run() // manages lifecycle, but reflection-based
samber/do:
i := do.New()
do.Provide(i, NewConfig)
do.Provide(i, NewDatabase) // auto shutdown + health check
do.Provide(i, NewUserStore)
do.Provide(i, NewUserService)
api := do.MustInvoke[*API](i)
api.Run()
// defer i.Shutdown() — handles all cleanup automatically
DI makes testing straightforward — inject mocks instead of real implementations:
// Define a mock
type MockUserStore struct {
users map[string]*User
}
func (m *MockUserStore) FindByID(ctx context.Context, id string) (*User, error) {
u, ok := m.users[id]
if !ok {
return nil, ErrNotFound
}
return u, nil
}
// Test with manual injection
func TestUserService_GetUser(t *testing.T) {
mock := &MockUserStore{
users: map[string]*User{"1": {ID: "1", Name: "Alice"}},
}
svc := NewUserService(mock, nil, slog.Default())
user, err := svc.GetUser(context.Background(), "1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if user.Name != "Alice" {
t.Errorf("got %q, want %q", user.Name, "Alice")
}
}
Container cloning creates an isolated copy where you override only the services you need to mock:
func TestUserService_WithDo(t *testing.T) {
// Create a test injector with mock implementation
testInjector := do.New()
// Provide the mock UserStore interface
do.OverrideValue[UserStore](testInjector, &MockUserStore{
users: map[string]*User{"1": {ID: "1", Name: "Alice"}},
})
// Provide other real services as needed
do.Provide[*slog.Logger](testInjector, func(i *do.Injector) (*slog.Logger, error) {
return slog.Default(), nil
})
svc := do.MustInvoke[*UserService](testInjector)
user, err := svc.GetUser(context.Background(), "1")
// ... assertions
}
This 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).
| Signal | Action | | --- | --- | | < 10 services, simple dependencies | Stay with manual constructor injection | | 10-20 services, some cross-cutting concerns | Consider a DI library | | 20+ services, lifecycle management needed | Strongly recommended | | Need health checks, graceful shutdown | Use a library with built-in lifecycle support | | Team unfamiliar with DI concepts | Start manual, migrate incrementally |
| Mistake | Fix |
| --- | --- |
| Global variables as dependencies | Pass through constructors or DI container |
| init() for service setup | Explicit initialization in main() or container |
| Depending on concrete types | Accept interfaces at consumption boundaries |
| Passing the container everywhere (service locator) | Inject specific dependencies, not the container |
| Deep dependency chains (A->B->C->D->E) | Flatten — most services should depend on repositories and config directly |
| Creating a new container per request | One container per application; use scopes for request-level isolation |
golang-samber-do skill for detailed samber/do usage patternsgolang-structs-interfaces skill for interface design and compositiongolang-testing skill for testing with dependency injectiongolang-project-layout skill for DI initialization placementdevelopment
Vue 3 debugging and error handling for runtime errors, warnings, async failures, and SSR/hydration issues. Use when diagnosing or fixing Vue issues.
development
MUST be used for Vue.js tasks. Strongly recommends Composition API with `<script setup>` and TypeScript as the standard approach. Covers Vue 3, SSR, Volar, vue-tsc. Load for any Vue, .vue files, Vue Router, Pinia, or Vite with Vue work. ALWAYS use Composition API unless the project explicitly requires Options API.
development
GORM Gen 类型安全 DAO 代码生成,基于 github.com/rockcookies/go-gen(rockcookies fork)。涵盖代码生成配置、模型生成、查询构建、增删改查、关联关系、动态 SQL 注解、事务处理、datatypes 自定义字段类型(JSON/JSONMap/JSONSlice/JSONType/Date/UUID)、soft_delete 软删除插件(unix 时间戳/flag 模式),以及 fork 专有功能:Tmpl 运行时模板覆写(18 个模板)、Unsafe 底层方法(UnsafeSetDB/Alias/ModelType/TableName)、IGenericsDo[T,E] 泛型接口。使用时机:需要从数据库生成 DAO 代码(GenerateModel/GenerateModelAs)、编写 DAL 查询(DO 链式调用、DaoScope、事务、关联加载)、配置生成器(gen.Config、ModelOpt、FieldGORMTag、FieldModify、FieldType、Tmpl 自定义模板)、使用 datatypes(JSONMap、JSONSlice、JSONQuery、JSONSet)或 soft_delete(DeletedAt、softDelete:milli、deleteOpts)时使用本技能。当用户消息中包含以下任一关键词(go-gen、gorm-gen、GenerateModelAs、ModelOpt、FieldGORMTag、FieldModify、DaoScope、LoadOneToMany、LoadManyToMany、IGenericsDo、UnsafeSetDB、datatypes、JSONMap、JSONSlice、JSONQuery、soft_delete、softDelete、DeletedAt),或用户明确请求 GORM Gen 代码生成/DAO 编写时触发本技能。
development
轻量级 Go HTTP 客户端库,基于 github.com/rockcookies/go-fetch(零外部依赖)。涵盖 Dispatcher 初始化与中间件、Request 链式构建(RequestFunc 与 Middleware 分层)、Response 解码(JSON/XML/流)、请求体编码(JSON/XML/Form/Multipart/BodyGet)、URL 参数(PrepareURLMiddleware/URLOptions)、Header/Cookie 管理(ApplyHeader/ApplyCookie 与 Context)、中间件组合(Dispatcher/Request/Do 三层)、HTTP 交换日志(dump.New/dump.Transport/过滤器/WithRequestRedactor/WithResponseRedactor/SlogWriter)。使用时机:需要发起 HTTP 请求(GET/POST/PUT/PATCH/DELETE,均需 context.Context)、上传文件(Multipart/GetReader)、配置全局认证头(dispatcher.Use)、记录 HTTP 交换日志(dump.New、WithFilter、DefaultRedactor)、构建可复用的请求基础(Request.Clone)时使用本技能。当用户消息中包含以下任一关键词(go-fetch、NewDispatcher、NewDispatcherWithTransport、RequestFunc、PreFuncs、UseFuncs、BodyGet、MultipartField、dump.New、WithFilter、WithRequestRedactor、WithResponseRedactor、DefaultRedactor、DumpOptions、SlogWriter、URLOptions、PrepareURLMiddleware、PathParams、SetURLOptions、WithURLOptions、ApplyHeader、SetHeaderOptions、WithHeaderOptions、ApplyCookie、SetCookieOptions、WithCookieOptions、HandlerFunc、fetch.Handler、fetch.Middleware、dispatcher.Use、resp.Close、resp.JSON、resp.XML),或用户明确请求 go-fetch HTTP 客户端用法时触发本技能。