User guide
Basics
Wire has two core concepts: providers and injectors.
Defining providers
The primary mechanism in Wire is the provider: a function that can produce a value. These are ordinary Go functions.
package foobarbaz
type Foo struct {
X int
}
// ProvideFoo returns a Foo.
func ProvideFoo() Foo {
return Foo{X: 42}
}Provider functions must be exported to be usable from other packages, just like ordinary functions.
Providers can specify dependencies with parameters:
package foobarbaz
// ...
type Bar struct {
X int
}
// ProvideBar returns a Bar: a negative Foo.
func ProvideBar(foo Foo) Bar {
return Bar{X: -foo.X}
}Providers can also return errors:
package foobarbaz
import (
"context"
"errors"
)
// ...
type Baz struct {
X int
}
// ProvideBaz returns a value if Bar is not zero.
func ProvideBaz(ctx context.Context, bar Bar) (Baz, error) {
if bar.X == 0 {
return Baz{}, errors.New("cannot provide baz when bar is zero")
}
return Baz{X: bar.X}, nil
}Provider sets
Providers can be grouped into provider sets. This is useful when several
providers are frequently used together. To add them to a new set called
SuperSet, use wire.NewSet:
package foobarbaz
import (
// ...
"github.com/wireinject/wire"
)
// ...
var SuperSet = wire.NewSet(ProvideFoo, ProvideBar, ProvideBaz)You can also add other provider sets to a provider set:
package foobarbaz
import (
// ...
"example.com/some/other/pkg"
)
// ...
var MegaSet = wire.NewSet(SuperSet, pkg.OtherSet)Injectors
An application wires up these providers with an injector: a function that calls providers in dependency order. With Wire you write the injector’s signature, and Wire generates the function’s body.
An injector is declared by writing a function declaration whose body is a call to
wire.Build. The return values don’t matter as long as they are of the correct
type — the values themselves are ignored in the generated code. Say the providers
above live in a package called example.com/foobarbaz. The following declares an
injector that obtains a Baz:
//go:build wireinject
// +build wireinject
// The build tag makes sure the stub is not built in the final build.
package main
import (
"context"
"github.com/wireinject/wire"
"example.com/foobarbaz"
)
func initializeBaz(ctx context.Context) (foobarbaz.Baz, error) {
wire.Build(foobarbaz.MegaSet)
return foobarbaz.Baz{}, nil
}Like providers, injectors can be parameterized on inputs (which then get sent to
providers) and can return errors. The arguments to wire.Build are the same as
those to wire.NewSet: together they form a provider set, and that set is what
gets used during code generation for this injector.
Any non-injector declarations found in a file with injectors are copied into the generated file.
Generate the injector by invoking Wire in the package directory:
wireWire produces an implementation of the injector in a file called wire_gen.go
that looks something like this:
// Code generated by Wire. DO NOT EDIT.
//go:generate go run -mod=mod github.com/wireinject/wire/cmd/wire
//go:build !wireinject
// +build !wireinject
package main
import (
"example.com/foobarbaz"
)
func initializeBaz(ctx context.Context) (foobarbaz.Baz, error) {
foo := foobarbaz.ProvideFoo()
bar := foobarbaz.ProvideBar(foo)
baz, err := foobarbaz.ProvideBaz(ctx, bar)
if err != nil {
return foobarbaz.Baz{}, err
}
return baz, nil
}As you can see, the output is very close to what a developer would write by hand. There is also little dependency on Wire at runtime: all of the written code is normal Go, and can be used without Wire.
Once wire_gen.go exists you can regenerate it with
go generate.
Generating injectors is only one of the things the wire binary does: it can also
check your wiring, describe your provider sets and draw the dependency graph as a
diagram. See the command line reference for all the commands.
Advanced features
The following features all build on top of providers and injectors.
Binding interfaces
Frequently, dependency injection is used to bind a concrete implementation for an interface. Wire matches inputs to outputs via type identity, so the inclination might be to create a provider that returns an interface type. That would not be idiomatic, though: Go best practice is to return concrete types. Instead, declare an interface binding in a provider set:
type Fooer interface {
Foo() string
}
type MyFooer string
func (b *MyFooer) Foo() string {
return string(*b)
}
func provideMyFooer() *MyFooer {
b := new(MyFooer)
*b = "Hello, World!"
return b
}
type Bar string
func provideBar(f Fooer) string {
// f will be a *MyFooer.
return f.Foo()
}
var Set = wire.NewSet(
provideMyFooer,
wire.Bind(new(Fooer), new(*MyFooer)),
provideBar)The first argument to wire.Bind is a pointer to a value of the desired interface
type, and the second is a pointer to a value of the type that implements it. Any
set that includes an interface binding must also have a provider in the same set
that provides the concrete type.
Struct providers
Structs can be constructed from provided types. Use wire.Struct to name the
struct to construct and the field(s) to inject; the injector fills each field
using the provider for that field’s type.
For a resulting struct type S, wire.Struct provides both S and *S. Given
the following providers:
type Foo int
type Bar int
func ProvideFoo() Foo {/* ... */}
func ProvideBar() Bar {/* ... */}
type FooBar struct {
MyFoo Foo
MyBar Bar
}
var Set = wire.NewSet(
ProvideFoo,
ProvideBar,
wire.Struct(new(FooBar), "MyFoo", "MyBar"))a generated injector for FooBar looks like this:
func injectFooBar() FooBar {
foo := ProvideFoo()
bar := ProvideBar()
fooBar := FooBar{
MyFoo: foo,
MyBar: bar,
}
return fooBar
}The first argument to wire.Struct is a pointer to the desired struct type; the
subsequent arguments are the names of fields to inject. The special string "*"
is a shortcut for all fields, so wire.Struct(new(FooBar), "*") produces the same
result as above.
To inject only "MyFoo", change the set to:
var Set = wire.NewSet(
ProvideFoo,
wire.Struct(new(FooBar), "MyFoo"))and the generated injector becomes:
func injectFooBar() FooBar {
foo := ProvideFoo()
fooBar := FooBar{
MyFoo: foo,
}
return fooBar
}If the injector returned *FooBar instead of FooBar, the generated code would be:
func injectFooBar() *FooBar {
foo := ProvideFoo()
fooBar := &FooBar{
MyFoo: foo,
}
return fooBar
}It is sometimes useful to prevent certain fields from being filled in by the
injector, especially when passing * to wire.Struct. Tag a field with
`wire:"-"` to have Wire ignore it:
type Foo struct {
mu sync.Mutex `wire:"-"`
Bar Bar
}When you provide Foo using wire.Struct(new(Foo), "*"), Wire omits the mu
field automatically. It is an error to name a prevented field explicitly, as in
wire.Struct(new(Foo), "mu").
Binding values
Occasionally it is useful to bind a basic value (usually nil) to a type. Rather
than having injectors depend on a throwaway provider function, add a value
expression to a provider set:
type Foo struct {
X int
}
func injectFoo() Foo {
wire.Build(wire.Value(Foo{X: 42}))
return Foo{}
}The generated injector:
func injectFoo() Foo {
foo := _wireFooValue
return foo
}
var (
_wireFooValue = Foo{X: 42}
)Note that the expression is copied to the injector’s package, and references to variables are evaluated during that package’s initialization. Wire reports an error if the expression calls any functions or receives from any channels.
For interface values, use InterfaceValue:
func injectReader() io.Reader {
wire.Build(wire.InterfaceValue(new(io.Reader), os.Stdin))
return nil
}Using fields of a struct as providers
Sometimes the providers you want are fields of a struct. If you find yourself
writing a provider like getS below to promote struct fields into provided types:
type Foo struct {
S string
N int
F float64
}
func getS(foo Foo) string {
// Bad! Use wire.FieldsOf instead.
return foo.S
}
func provideFoo() Foo {
return Foo{ S: "Hello, World!", N: 1, F: 3.14 }
}
func injectedMessage() string {
wire.Build(
provideFoo,
getS)
return ""
}use wire.FieldsOf instead and drop getS entirely:
func injectedMessage() string {
wire.Build(
provideFoo,
wire.FieldsOf(new(Foo), "S"))
return ""
}The generated injector:
func injectedMessage() string {
foo := provideFoo()
string2 := foo.S
return string2
}Add as many field names to a wire.FieldsOf call as you like. For a given field
type T, FieldsOf provides at least T; if the struct argument is a pointer to
a struct, it also provides *T.
Cleanup functions
If a provider creates a value that needs to be cleaned up (closing a file, say), it can return a closure to do so. The injector uses it either to return an aggregated cleanup function to the caller, or to clean up the resource when a provider called later in the injector returns an error.
func provideFile(log Logger, path Path) (*os.File, func(), error) {
f, err := os.Open(string(path))
if err != nil {
return nil, nil, err
}
cleanup := func() {
if err := f.Close(); err != nil {
log.Log(err)
}
}
return f, cleanup, nil
}A cleanup function is guaranteed to be called before the cleanup function of any
of the provider’s inputs, and must have the signature func().
Alternate injector syntax
If you grow weary of writing return foobarbaz.Foo{}, nil at the end of your
injector, write it more concisely with a panic:
func injectFoo() Foo {
panic(wire.Build(/* ... */))
}