golang-samber-do
samber/cc-skills-golang
Type-safe dependency injection for Go using generics—service containers, lifecycle management, and graceful shutdown.
What is golang-samber-do?
samber/do is a Go 1.18+ DI toolkit providing type-safe service containers with lazy, eager, transient, and value registration modes. Use it when adopting or refactoring to dependency injection, or when your codebase already imports github.com/samber/do/v2.
- Register services as lazy (on-demand), eager (at startup), transient (new each time), or pre-created values
- Invoke services by type with error handling or panic-on-error variants
- Organize service registration into packages for modular composition
- Support named services to register multiple instances of the same type
- Enable graceful shutdown and signal handling for application lifecycle
- Inject dependencies into struct fields using tags
How to install golang-samber-do
npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-do- Go 1.18 or later
- github.com/samber/do/v2 installed via `go get -u github.com/samber/do/v2`
How to use golang-samber-do
- 1.Define service interfaces and concrete implementations following 'Accept Interfaces, Return Structs'
- 2.Create provider functions matching `func(i do.Injector) (T, error)` signature
- 3.Register services using `do.Provide()`, `do.ProvideValue()`, `do.ProvideTransient()`, or `do.ProvideNamed()` variants
- 4.Organize related registrations into packages using `do.Package()`
- 5.Invoke services at the composition root using `do.Invoke[T]()` or `do.MustInvoke[T]()`
- 6.Call `injector.ShutdownOnSignalsWithContext()` in main() for graceful shutdown
Use cases
- Setting up a web service with database, cache, and logger dependencies at the composition root
- Refactoring manual constructor injection into a type-safe container
- Organizing microservice infrastructure (database, queue, config) into reusable packages
- Testing by cloning the injector and overriding specific services without touching production code
- Managing request-scoped vs. global-scoped services in multi-tenant applications
- Go backend developers building applications with multiple interdependent services
- Teams adopting dependency injection to improve testability and modularity
- Architects designing service-oriented or microservice architectures in Go
- Contributors to projects already using samber/do v2
golang-samber-do FAQ
Use v2 only. The skill explicitly states DO NOT USE v1—install v2 via `go get -u github.com/samber/do/v2`.
Use `Invoke()` when the service might not exist or initialization might fail; handle the error explicitly. Use `MustInvoke()` only at the composition root where you are confident the service was registered and initialized successfully.
Use `do.ProvideNamed()` to register with a string key, then invoke with `do.MustInvokeNamed[T](injector, name)`.
Yes. Use `do.InvokeStruct[T]()` or `do.MustInvokeStruct[T]()` to inject dependencies into struct fields marked with tags. See the Advanced Usage and Testing references for details.
Clone the injector and override specific services for testing without modifying production code. See the Testing reference in the skill documentation.
Full instructions (SKILL.md)
Source of truth, from samber/cc-skills-golang.
name: golang-samber-do description: "Dependency injection in Golang using samber/do — service containers, lifecycle management, scopes, health checks, graceful shutdown, and module organization. Apply when using or adopting samber/do, when the codebase imports github.com/samber/do or github.com/samber/do/v2, or when refactoring manual constructor injection into a DI container." user-invocable: true license: MIT compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang. metadata: author: samber version: "1.2.2" openclaw: emoji: "💉" homepage: https://github.com/samber/cc-skills-golang requires: bins: - go install: [] skill-library-version: "2.0.0" allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs
Persona: You are a Go architect setting up dependency injection. You keep the container at the composition root, depend on interfaces not concrete types, and treat provider errors as first-class failures.
Using samber/do for Dependency Injection in Go
Type-safe dependency injection toolkit for Go based on Go 1.18+ generics.
Official Resources:
This skill is not exhaustive. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform. For Go package docs, versions, symbols, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill.
DO NOT USE v1 OF THIS LIBRARY. INSTALL v2 INSTEAD:
go get -u github.com/samber/do/v2
Core Concepts
The Injector (Container)
import "github.com/samber/do/v2"
injector := do.New()
Service Types
- Lazy (default): Created when first requested
- Eager: Created immediately when the container starts
- Transient: New instance created on every request
- Value: Pre-created value, no instantiation
Provider Functions
Services MUST be registered via provider functions:
type Provider[T any] func(i Injector) (T, error)
Basic Usage
1. Define and Register Services
Follow "Accept Interfaces, Return Structs":
// Register a service (lazy by default)
do.Provide(injector, func(i do.Injector) (Database, error) {
return &PostgreSQLDatabase{connString: "postgres://..."}, nil
})
// Register a pre-created value
do.ProvideValue(injector, &Config{Port: 8080})
// Register a transient service (new instance each time)
do.ProvideTransient(injector, func(i do.Injector) (*Logger, error) {
return &Logger{}, nil
})
// Register an eager service (created immediately at startup)
do.ProvideValue(injector, &Config{Port: 8080})
2. Invoke Services
The container MUST only be accessed at the composition root:
// Invoke with error handling
db, err := do.Invoke[Database](injector)
// MustInvoke panics on error (use when confident service exists)
db := do.MustInvoke[Database](injector)
3. Service Dependencies
func NewUserService(i do.Injector) (UserService, error) {
db := do.MustInvoke[Database](i)
cache := do.MustInvoke[Cache](i)
return &userService{db: db, cache: cache}, nil
}
do.Provide(injector, NewUserService)
4. Implicit Aliasing (Preferred)
Register a concrete type and invoke as an interface without explicit aliasing:
// Register concrete type
do.Provide(injector, func(i do.Injector) (*PostgreSQLDatabase, error) {
return &PostgreSQLDatabase{}, nil
})
// Invoke directly as interface (implicit aliasing)
db := do.MustInvokeAs[Database](injector)
5. Named Services
Register multiple services of the same type:
do.ProvideNamed(injector, "primary-db", func(i do.Injector) (*Database, error) {
return &Database{URL: "postgres://primary..."}, nil
})
mainDB := do.MustInvokeNamed[*Database](injector, "primary-db")
Package Organization
Use do.Package() to organize service registration by module:
// infrastructure/package.go
var Package = do.Package(
do.Lazy(func(i do.Injector) (*postgres.DB, error) {
cfg := do.MustInvoke[*Config](i)
return postgres.Connect(cfg.DatabaseURL)
}),
do.Lazy(func(i do.Injector) (*redis.Client, error) {
cfg := do.MustInvoke[*Config](i)
return redis.NewClient(cfg.RedisURL), nil
}),
)
// main.go
injector := do.New(infrastructure.Package, service.Package)
Full Application Setup
func main() {
injector := do.New(
infrastructure.Package,
repository.Package,
service.Package,
transport.Package,
)
server := do.MustInvoke[*http.Server](injector)
go server.ListenAndServe()
_ = injector.ShutdownOnSignalsWithContext(context.Background(), os.Interrupt)
}
Best Practices
- Depend on interfaces, not concrete types — lets you swap implementations in tests without touching production code
- Each service should have one job — services with multiple responsibilities are harder to test and harder to replace
- Keep dependency trees shallow — chains beyond 3-4 levels make initialization order fragile and errors harder to trace
- Handle errors in provider functions — a silently failing provider creates a broken service that crashes later in unexpected places
- Use scopes to organize services by lifecycle — request-scoped services prevent leaks, global services prevent redundant initialization
For scopes, lifecycle management, struct injection, and debugging, see Advanced Usage.
For testing patterns (cloning, overrides, mocks), see Testing.
Quick Reference
Registration
| Function | Purpose |
|---|---|
do.Provide[T]() | Register lazy service (default) |
do.ProvideNamed[T]() | Register named lazy service |
do.ProvideValue[T]() | Register pre-created value |
do.ProvideNamedValue[T]() | Register named value |
do.ProvideTransient[T]() | Register new instance each time |
do.ProvideNamedTransient[T]() | Register named transient service |
do.Package() | Group service registrations |
Invocation
| Function | Purpose |
|---|---|
do.Invoke[T]() | Get service (with error) |
do.InvokeNamed[T]() | Get named service |
do.InvokeAs[T]() | Get first service matching interface |
do.InvokeStruct[T]() | Inject into struct fields using tags |
do.MustInvoke[T]() | Get service (panic on error) |
do.MustInvokeNamed[T]() | Get named service (panic on error) |
do.MustInvokeAs[T]() | Get service by interface (panic on error) |
do.MustInvokeStruct[T]() | Inject into struct (panic on error) |
Cross-References
- → See
samber/cc-skills-golang@golang-dependency-injectionskill for DI concepts, comparison, and when to adopt a DI library - → See
samber/cc-skills-golang@golang-structs-interfacesskill for interface design patterns - → See
samber/cc-skills-golang@golang-testingskill for general testing patterns
Related skills
More from samber/cc-skills-golang and the wider catalog.
golang-code-style
Go code style conventions for clarity, control flow, and readability—line breaking, variable declarations, and when comments help.
golang-error-handling
Idiomatic Go error handling: wrapping, inspection, structured logging, and production-grade error tracking.
golang-performance
Go performance optimization patterns: identify bottlenecks with profiling, then apply the right fix.
golang-design-patterns
Idiomatic Go design patterns: functional options, constructors, error handling, resource lifecycle, graceful shutdown, and resilience.
golang-testing
Production-ready Go tests with table-driven patterns, testify integration, parallel execution, fuzzing, and leak detection.
golang-security
Security best practices and vulnerability prevention for Go code—injection, crypto, secrets, and authentication.