Skills Agentes

Golang Google Wire

Inyección de dependencias en tiempo de compilación en Golang con google/wire — wire.NewSet, wire.Build, wire.Bind, wire.Struct, wire.Value, injectores wireinject y wire_gen.go generado.

Reemplaza a: DI en tiempo de ejecución con dig / fx / samber/do

Solicitaread edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent webfetch mcp__context7__resolve-library-id mcp__context7__query-docs bash(wire:*) bash(godig:*) bash(gopls:*) lsp mcp__gopls__*
Estrellas
3k

en todo el repo

Actividad
62

0–100, la ruta de este skill

Actualizado
el mes pasado

último commit aquí

Commits
9

últimos 90 días

Contexto
2.8k tok

130 tok en reposo

Paquete
5 archivos

44 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add samber/cc-skills-golang --skill golang-google-wire --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Configura providers, wire.NewSet y injectores wireinject para generar wire_gen.go con wire.Build
  • Aplica bindings de interfaz con wire.Bind y estructura providers con wire.Struct, wire.Value y wire.FieldsOf
  • Gestiona funciones de cleanup encadenadas en orden inverso desde providers
  • Ejecuta el flujo de codegen con wire ./... y wire check ./... para validar el grafo

Úsalo cuando

  • Se está usando o adoptando google/wire
  • El código importa github.com/google/wire
  • Se está cableando el grafo de una aplicación en tiempo de compilación con wire.Build

No lo uses cuando

  • Se necesita DI en tiempo de ejecución con reflexión (usar samber/cc-skills-golang@golang-uber-dig)

Qué lo activa

Di cualquiera de estas frases y el agente debería cargar este skill.

  • Ayúdame a configurar wire.Build para mi aplicación
  • Necesito un provider set con wire.NewSet para mis repositorios
  • ¿Cómo declaro un wire.Bind para esta interfaz?
  • Genera el injector con //go:build wireinject
  • Por qué falla wire ./... tras cambiar un constructor

SKILL.md

En inglés

Persona: You are a Go architect using wire for compile-time DI. You let the compiler catch missing dependencies, treat wire_gen.go as committed source, and re-run wire ./... after every graph change.

Dependencies:

  • wire: go install github.com/google/wire/cmd/wire@latest

Using google/wire for Compile-Time Dependency Injection in Go

Code-generation DI toolkit. Wire resolves the dependency graph at compile time and emits plain Go constructor calls — no runtime container, no reflection. Errors appear when you run wire ./..., not at first request.

Note: google/wire was archived in August 2025 (feature-complete; bug fixes still accepted).

Official Resources: pkg.go.dev · github.com/google/wire · User Guide · Best Practices

This skill is not exhaustive. Please 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-dev skill (godig) — prefer it 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-gopls skill (gopls). Context7 remains a fallback for docs not indexed on pkg.go.dev.

go get -tool github.com/google/wire/cmd/wire@latest
go get github.com/google/wire

wire vs. Runtime DI

Concern wire dig / fx / samber/do
Resolution Compile time (codegen) Runtime (reflection)
Error detection wire ./... fails First Invoke/startup
Runtime container None — plain Go calls Present
Lifecycle hooks Not built in fx: OnStart/OnStop
Generated files wire_gen.go (committed) None

For lifecycle, lazy loading, and a full matrix see samber/cc-skills-golang@golang-dependency-injection.

Providers

A provider is any Go function — inputs are dependencies, outputs are provided types. Three return forms:

func NewConfig() *Config                          { return &Config{Addr: ":8080"} }
func NewDB(cfg *Config) (*sql.DB, error)          { return sql.Open("postgres", cfg.DSN) }
func NewRedis(cfg *Config) (*redis.Client, func(), error) { // cleanup chained in reverse order
    c := redis.NewClient(&redis.Options{Addr: cfg.RedisAddr})
    return c, func() { c.Close() }, nil
}

Provider Sets

wire.NewSet groups providers for reuse. Sets can reference other sets.

// infra/wire.go
var InfraSet = wire.NewSet(
    NewConfig,
    NewDB,
    NewRedis,
)

// service/wire.go
var ServiceSet = wire.NewSet(
    NewUserRepo,
    NewUserService,
    wire.Bind(new(UserStore), new(*UserRepo)), // interface binding
)

Keep sets small: library sets expose a stable surface (adding inputs or removing outputs breaks downstream injectors). One set per package is a useful default.

Injectors and //go:build wireinject

The injector file declares the initialization function. Wire generates its body into wire_gen.go and replaces the stub.

//go:build wireinject

package main

import "github.com/google/wire"

// Wire generates the body of this function.
func InitApp() (*App, func(), error) {
    wire.Build(InfraSet, ServiceSet, NewApp)
    return nil, nil, nil // replaced by codegen
}

The //go:build wireinject tag prevents the stub from being compiled into the binary — only wire_gen.go (which has no such tag) makes it through go build. Without this tag, both files define the same function, causing a compile error.

Alternative syntax when a dummy return is inconvenient:

func InitApp() (*App, func(), error) {
    panic(wire.Build(InfraSet, ServiceSet, NewApp))
}

Interface Bindings

Wire forbids implicit interface satisfaction — you must declare bindings explicitly so the graph is unambiguous when multiple types implement the same interface.

var Set = wire.NewSet(
    NewPostgresUserRepo,
    wire.Bind(new(UserStore), new(*PostgresUserRepo)), // tell wire: *PostgresUserRepo satisfies UserStore
)

Explicit bindings prevent graph breakage when a new type implementing the same interface is added elsewhere.

Struct Providers and Values

wire.Struct fills struct fields from the graph without a manual constructor. Tag fields wire:"-" to exclude them.

wire.Struct(new(Server), "Logger", "DB") // inject named fields
wire.Struct(new(Server), "*")            // inject all non-excluded fields
wire.Value(Foo{X: 42})                   // constant expression (no fn calls / channels)
wire.InterfaceValue(new(io.Reader), os.Stdin) // interface-typed literal
wire.FieldsOf(new(Config), "DSN", "Addr")    // promote struct fields as graph nodes

See advanced.md for the wire:"-" exclusion tag and wire.FieldsOf details.

Disambiguating Duplicate Types

Wire forbids two providers for the same type. Wrap the underlying type in distinct named types so each has exactly one provider:

type PrimaryDSN string
type ReplicaDSN string

Full Application Example

// wire.go — injector, excluded from binary via build tag
//go:build wireinject

package main

func InitApp() (*App, func(), error) {
    wire.Build(config.ConfigSet, infra.InfraSet, service.ServiceSet, NewApp)
    return nil, nil, nil
}

// main.go
func main() {
    app, cleanup, err := InitApp()
    if err != nil { log.Fatal(err) }
    defer cleanup()
    app.Run()
}

Wire generates wire_gen.go (plain Go, committed, DO NOT EDIT). For a full example with per-package sets, cleanup-heavy graphs, and generated output, see recipes.md.

Codegen Workflow

wire ./...           # regenerate all injectors in the module
wire check ./...     # validate graph without regenerating (fast CI check)

Run wire ./... after every constructor signature change. Add //go:generate go run github.com/google/wire/cmd/wire to injector files so go generate ./... also works. Commit wire_gen.go — it must stay in sync for CI builds.

Best Practices

  1. Never edit wire_gen.go — it is overwritten on every wire ./... run. Treat it as a build artifact that happens to be committed; source of truth is the provider and injector files.
  2. Always add //go:build wireinject to injector files — omitting it causes duplicate-symbol compile errors because both the stub and the generated file define the same function.
  3. Use named types to distinguish values of the same underlying type — wire enforces one provider per type; named types like type DSN string let you have PrimaryDSN and ReplicaDSN coexist.
  4. Keep library provider sets minimal and backward-compatible — adding new required inputs breaks downstream injectors; removing outputs does too. Introduce only newly-created types in the same release.
  5. Return (T, func(), error) from cleanup providers and let wire chain them — wire generates the correct reverse-order cleanup and handles partial failures (if construction fails midway, only already-built cleanups run).
  6. Keep injector files focused — one function per file, one package import at a time. Fat injectors with dozens of wire.Build arguments are hard to reason about; delegate to per-package sets.

Common Mistakes

Mistake Fix
Editing wire_gen.go manually Never edit it. Change providers or injectors and re-run wire ./....
Missing //go:build wireinject Add the tag as the very first line of every injector file.
Two providers returning *sql.DB Wrap with a named struct type: type PrimaryDB struct { *sql.DB } — Wire does not distinguish pointer type aliases.
Injecting an interface without wire.Bind Add wire.Bind(new(MyInterface), new(*MyImpl)) to the provider set.
Forgetting to re-run wire ./... after changes Run wire before go build; add it to go generate or a Makefile target.
Calling cleanup() without guarding for nil Wire returns nil cleanup on construction error; guard with if cleanup != nil { defer cleanup() }.

Testing

Wire generates plain Go constructors, so unit tests use manual injection — no container to clone or reset. For testing patterns (test injectors swapping real providers for fakes, CI stale-check for wire_gen.go), see testing.md.

Further Reading

  • advanced.md — cleanup chains, multiple injectors, set nesting, error catalogue, codegen flags, quick reference
  • recipes.md — HTTP server, multi-injector build, cleanup-heavy graph, CLI embedding
  • testing.md — test injectors, fake bindings, CI stale check

Cross-References

  • → See samber/cc-skills-golang@golang-dependency-injection skill for DI concepts and library comparison
  • → See samber/cc-skills-golang@golang-uber-dig skill for runtime reflection-based DI without lifecycle
  • → See samber/cc-skills-golang@golang-uber-fx skill for runtime DI with lifecycle hooks, modules, and signal-aware Run()
  • → See samber/cc-skills-golang@golang-samber-do skill for generics-based DI without reflection
  • → 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

If you encounter a bug or unexpected behavior in google/wire, open an issue at https://github.com/google/wire/issues.

Reproducido de samber/cc-skills-golang bajo licencia MIT. Leer esta página en markdown.

Archivos

5 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

Antes de instalar

Requiere el binario wire instalado (go install github.com/google/wire/cmd/wire@latest) y el módulo github.com/google/wire.

Detalles

Creador
samber
Licencia
MIT
Recursos incluidos
referencias
Código fuente
Ver SKILL.md

Etiquetas

Más de samber/cc-skills-golang

Este repo incluye 46 skills. Si instalas uno, normalmente ya tienes los demás.

Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters.

Costo de contexto al activarse
1.8k tok
Tamaño del paquete
5 archivos
Última actualización
hace 3 días
herramientas desarrollo

Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

Costo de contexto al activarse
3.3k tok
Tamaño del paquete
10 archivos
Última actualización
hace 28 días
testing qa

Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez.

Costo de contexto al activarse
3.8k tok
Tamaño del paquete
4 archivos
Última actualización
hace 20 días
herramientas desarrollo

Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
9 archivos
Última actualización
el mes pasado
herramientas desarrollo

Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración.

Costo de contexto al activarse
4.4k tok
Tamaño del paquete
6 archivos
Última actualización
el mes pasado
testing qa

Inyección de dependencias en Golang con samber/do: contenedores de servicios, gestión de ciclo de vida, scopes, health checks, apagado ordenado y organización en módulos.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
4 archivos
Última actualización
hace 22 días
herramientas desarrollo

Skills relacionados

Desarrollo de aplicaciones CLI en Go: estructura de comandos, flags, configuración por capas, versión embebida, exit codes, señales, completions y testing con cobra, viper o urfave/cli.

Costo de contexto al activarse
2.6k tok
Tamaño del paquete
14 archivos
Última actualización
hace 3 meses
herramientas desarrollo

Convenciones de estilo en Golang: longitud y corte de líneas, declaración de variables, claridad del control de flujo y cuándo los comentarios ayudan u estorban.

Costo de contexto al activarse
2.5k tok
Tamaño del paquete
3 archivos
Última actualización
el mes pasado
herramientas desarrollo

Patrones de concurrencia en Go: úsalo al escribir o revisar código concurrente con goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools o pipelines fan-out/fan-in.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
5 archivos
Última actualización
el mes pasado
herramientas desarrollo