Golang Samber Do
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides guidance on using samber/do, a generics-based dependency injection toolkit for Go 1.18+. It covers service registration, lifecycle management, scoping, and integration patterns to help developers move away from manual constructor injection. The skill emphasizes maintaining a clean composition root, using interfaces for decoupling, and leveraging the library's built-in support for health checks and graceful shutdowns.
What it does
- Registers services using lazy, eager, transient, or value-based providers.
- Organizes service registration into modular packages.
- Manages service lifecycles with health checks and graceful shutdown hooks.
- Supports hierarchical dependency scoping for better isolation.
- Provides utilities for struct-based injection using tags.
- Facilitates testing through container cloning and service overrides.
When to use it
- When adopting the samber/do library for dependency injection in a Go project.
- When refactoring manual constructor injection to reduce boilerplate.
- When you need to manage complex service lifecycles and dependencies in a type-safe manner.
- When organizing large Go applications into distinct, testable modules.
Advantages
- Type-safe dependency resolution using Go generics.
- Reduces manual wiring boilerplate in complex applications.
- Built-in support for graceful shutdowns and health monitoring.
- Easy to test via container cloning and mock overrides.
- Supports modular architecture through package-level registration.
Usage examples
- “How do I register a database service in samber/do?”
- You use do.Provide to register a provider function that returns the service, which will be lazily instantiated when first requested.
- “How can I mock a dependency for testing with samber/do?”
- You can clone the existing injector using injector.Clone() and then use do.OverrideValue to replace the production service with your mock.
- “What is the best way to handle service dependencies inside a provider?”
- Use do.MustInvoke[T](i) inside your provider function; the library will automatically recover any panics and convert them into errors at the composition root.
- “How do I organize my services into modules?”
- Use do.Package() to group related service registrations and pass these packages to the do.New() constructor in your main function.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/samber/golang-samber-do/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-samber-do.zip -d .agents/skills
Documentation by samber
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 — refer to library documentation and code examples for more information:
For Go package docs, symbols, versions, importers, and known vulnerabilities, → See
samber/cc-skills-golang@golang-pkg-go-devskill (godig), preferred over Context7 for Go package facts.To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See
samber/cc-skills-golang@golang-goplsskill (gopls).Context7 remains a fallback for docs not indexed on pkg.go.dev.
Install v2 — v1 is superseded and lacks the generics-based container, scopes, and lifecycle hooks documented below, so v1-era guidance misleads on every API in this skill:
go get -u github.com/samber/do/v2Core 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 — reserve for call sites outside the DI graph
// (e.g. an HTTP handler that must degrade gracefully instead of crashing)
db, err := do.Invoke[Database](injector)
// MustInvoke panics on error — preferred in providers, recovered by do.Invoke on the parent call
db := do.MustInvoke[Database](injector)Inside a provider function, always use do.MustInvoke (or MustInvokeAs/MustInvokeNamed/MustInvokeStruct) rather than the error-returning variant:
A provider already returns
(T, error), so propagating a dependency failure withdo.Invokecosts an extraif err != nil { return nil, err }on every call.do.MustInvokepanics instead, but samber/do correctly catches and recovers that panic at the enclosingInvokecall and converts it back into a regular error — this recover happens inside the library itself, not in caller code, soMustInvokeis safe to use inside providers.The failure still surfaces as an error at the composition root, just without the manual boilerplate in every provider.
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
Use
do.MustInvoke*inside provider functions instead ofdo.Invoke*— samber/do correctly catches and recovers the panic at the outerInvokecall, turning it back into a returned error, so it's safe to use inside providers and you get the same error propagation without the boilerplate
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
Files
- ATTRIBUTION.mdAdded by AutoGineer905 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md9.1 KiB
- evals/evals.json11.6 KiB
- references/advanced.md5.7 KiB
- references/testing.md1.4 KiB
references/advanced.md
Advanced Usage
Table of Contents
Scopes (Module Tree)
Explicit Service Aliasing
Struct Injection
Lifecycle Management
Health Checks
Graceful Shutdown
Debugging
List Services
Explain Injector
Migration from Manual DI
Quick Reference
Aliasing
Lifecycle & Health
Container Management
Debugging
Scopes (Module Tree)
Scopes SHOULD be used to organize services by module:
root := do.New()
// Register shared services in root
do.Provide(root, func(i do.Injector) (Database, error) {
return &Database{}, nil
})
// Create child scope
apiScope := root.Scope("api")
// Services in apiScope can access root services
do.Provide(apiScope, func(i do.Injector) (UserService, error) {
db := do.MustInvoke[Database](i) // from root
return &userService{db: db}, nil
})
// Child scopes are isolated from each other
userScope := root.Scope("user")Organize services by lifecycle and visibility:
root := do.New()
// Global/stateless services in root
do.Provide(root, NewConfig)
do.Provide(root, NewLogger)
// Request-scoped services
requestScope := root.Scope("request")
do.Provide(requestScope, NewRequestContext)Explicit Service Aliasing
For rare cases when you need to adapt to legacy code:
do.Provide(injector, func(i do.Injector) (*PostgreSQLDatabase, error) {
return &PostgreSQLDatabase{}, nil
})
do.MustAs[*PostgreSQLDatabase, Database](injector)
// Now both work:
db1 := do.MustInvoke[*PostgreSQLDatabase](injector)
db2 := do.MustInvoke[Database](injector)Prefer implicit aliasing with InvokeAs() in most cases.
Struct Injection
Inject services directly into struct fields using tags:
type App struct {
Database *Database `do:""`
Logger *Logger `do:"app-logger"`
Config *Config `do:""`
}
app := do.MustInvokeStruct[App](injector)Lifecycle Management
Health Checks
Implement the Healthchecker interface:
func (d *Database) HealthCheck() error {
return d.conn.Ping()
}
// With context support:
func (d *Database) HealthCheck(ctx context.Context) error {
return d.conn.PingContext(ctx)
}
// Check health
if err := do.HealthCheck[Database](injector); err != nil {
log.Printf("Database unhealthy: %v", err)
}Graceful Shutdown
Implement the Shutdowner interface (4 variants):
// Simple
func (d *Database) Shutdown() { d.conn.Close() }
// With context
func (d *Database) Shutdown(ctx context.Context) { d.conn.Close() }
// With error
func (d *Database) Shutdown() error { return d.conn.Close() }
// With context + error (most flexible)
func (d *Database) Shutdown(ctx context.Context) error { return d.conn.Close() }Shutdown with timeout:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
report := injector.ShutdownWithContext(ctx)Debugging
List Services
services := injector.ListProvidedServices()
for _, svc := range services {
fmt.Printf("%s: %s\n", svc.ScopeName, svc.Service)
}Explain Injector
explanation := do.ExplainInjector(injector)
fmt.Println(explanation.String())Migration from Manual DI
Before (manual):
func main() {
config := &Config{Port: 8080}
db := NewDatabase(config)
userRepo := NewUserRepository(db)
userService := NewUserService(userRepo)
api := NewAPI(userService)
}After (with do):
func main() {
injector := do.New()
do.Provide(injector, func(i do.Injector) (*Config, error) {
return &Config{Port: 8080}, nil
})
do.Provide(injector, NewDatabase)
// ... register other services
api := do.MustInvoke[*API](injector)
}Quick Reference
Aliasing
| Function | Purpose |
|---|---|
do.As[Initial, Alias]() | Create type alias |
do.AsNamed[Initial, Alias]() | Create named type alias |
Lifecycle & Health
| Function | Purpose |
|---|---|
do.HealthCheck[T]() | Check service health |
do.HealthCheckNamed() | Check named service health |
do.HealthCheckWithContext[T]() | Health check with timeout |
do.Shutdown[T]() | Gracefully shutdown service |
do.ShutdownNamed() | Shutdown named service |
do.ShutdownWithContext[T]() | Shutdown with timeout |
do.MustShutdown[T]() | Shutdown (panic on error) |
Container Management
| Function | Purpose |
|---|---|
do.New() | Create new root container |
do.NewWithOpts() | Create container with options |
injector.Scope() | Create child scope |
Debugging
| Function | Purpose |
|---|---|
do.ExplainInjector() | Visualize scope tree and services |
do.ExplainService[T]() | Get service details and dependencies |
do.NameOf[T]() | Get service name (use sparingly) |
injector.ListProvidedServices() | List all available services |
injector.ListInvokedServices() | List invoked services only |
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-samber-do · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-samber-do.zip