golang-samber-do

por samber

Inyección de dependencias en Golang usando samber/do — contenedores de servicios, gestión del ciclo de vida, ámbitos, verificaciones de salud, apagado controlado y organización de módulos. Aplicar cuando se use o adopte samber/do, cuando el código base importe github.com/samber/do o github.com/samber/do/v2, o cuando se refactorice la inyección manual de constructores en un contenedor DI.

npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-do

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.

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

  1. Depend on interfaces, not concrete types — lets you swap implementations in tests without touching production code
  2. Each service should have one job — services with multiple responsibilities are harder to test and harder to replace
  3. Keep dependency trees shallow — chains beyond 3-4 levels make initialization order fragile and errors harder to trace
  4. Handle errors in provider functions — a silently failing provider creates a broken service that crashes later in unexpected places
  5. 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

FunctionPurpose
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

FunctionPurpose
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-injection skill for DI concepts, comparison, and when to adopt a DI library
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for interface design patterns
  • → See samber/cc-skills-golang@golang-testing skill for general testing patterns

Más skills de samber

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
Patrones de diseño idiomáticos en Golang: opciones funcionales, constructores, flujo y cascada de errores, gestión y ciclo de vida de recursos, apagado elegante, resiliencia, arquitectura, inyección de dependencias, manejo de datos, streaming y más. Aplicar al elegir explícitamente entre patrones arquitectónicos, implementar opciones funcionales, diseñar APIs de constructores, configurar un apagado elegante, aplicar patrones de resiliencia o preguntar qué patrón idiomático de Go se ajusta a un problema específico.
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Patrones y metodología de optimización de rendimiento en Golang: si hay un cuello de botella X, entonces aplica Y. Cubre reducción de asignaciones, eficiencia de CPU, diseño de memoria, ajuste de GC, pooling, caching y optimización de rutas críticas. Úsalo cuando el perfilado o los benchmarks hayan identificado un cuello de botella y necesites el patrón de optimización adecuado para solucionarlo. También úsalo al realizar una revisión de código de rendimiento para sugerir mejoras o benchmarks que ayuden a identificar ganancias rápidas de rendimiento. No es para metodología de medición (→...
developmentcode-review
golang-security
samber
Prácticas recomendadas de seguridad y prevención de vulnerabilidades para Golang. Abarca inyección (SQL, comandos, XSS), criptografía, seguridad del sistema de archivos, seguridad de red, cookies, gestión de secretos, seguridad de memoria y registro. Aplicar al escribir, revisar o auditar código Go por seguridad, o al trabajar en cualquier código riesgoso que involucre criptografía, E/S, gestión de secretos, manejo de entrada de usuario o autenticación. Incluye configuración de herramientas de seguridad.
securitycode-reviewdevelopment
golang-database
samber
Guía completa para el acceso a bases de datos en Go: consultas parametrizadas, escaneo de estructuras, columnas anulables, transacciones, niveles de aislamiento, SELECT FOR UPDATE, pool de conexiones, procesamiento por lotes, propagación de contexto y herramientas de migración. Úsela al escribir, revisar o depurar código Golang que interactúe con PostgreSQL, MariaDB, MySQL o SQLite; para pruebas de bases de datos; o para preguntas sobre database/sql, sqlx o pgx. NO genera esquemas de bases de datos ni SQL de migración.
developmentdatabase
golang-lint
samber
Mejores prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir advertencias con directivas nolint, interpretar la salida de lint y seleccionar linters. Úselo al configurar golangci-lint, preguntar sobre advertencias de lint o supresiones nolint, configurar herramientas de calidad de código o elegir linters. También úselo cuando el usuario mencione golangci-lint, go vet, staticcheck o revive.
developmentcode-reviewtesting