di-go

Dependency injection you can read.

di-go wires Go services with generics and plain factory functions. Register a type, ask for it, and get it back typed. No code generation, and no reflection over constructor signatures.

go get github.com/pixie-sh/di-go

Go 1.24+. MIT licensed. The full reference is in the README.

The problem

Wiring by hand does not scale. Wiring by magic is hard to debug.

Every service starts with a main.go that builds everything in the right order. It grows with each dependency, and a container that hides the wiring makes a missing dependency hard to trace.

By hand, in main.go

cfg := loadConfig()
primary := newDatabase(cfg.Primary)
replica := newDatabase(cfg.Replica)
cache := newCache(cfg.Cache)
users := newUserRepository(primary)
orders := newOrderRepository(primary, replica)
mailer := newMailer(cfg.Mail)
billing := newBilling(orders, mailer, cache)
api := newAPI(users, orders, billing)
// ...and again in every test and every binary

The order is yours to maintain, and every binary repeats it.

With di-go

di.Register[*Billing](func(ctx di.Context, _ *di.RegistryOpts) (*Billing, error) {
    orders, err := di.Create[*OrderRepository](ctx)
    if err != nil {
        return nil, err
    }
    mailer, err := di.Create[*Mailer](ctx)
    if err != nil {
        return nil, err
    }
    return newBilling(orders, mailer), nil
})

api, err := di.Create[*API](ctx)

Each type says what it needs. The graph is built when you ask for it.

A dependency is a function

The factory is ordinary Go. You can read it, step through it and set a breakpoint in it.

The compiler checks the types

Create[*API](ctx) returns a *API. There are no casts and no interface{} at the call site.

Errors point at the cause

A failed creation names the missing dependency and the path through the graph that led to it.

How it works

Register a factory. Ask for the type.

Registration order does not matter. Nothing is built until Create is called, and then only what the requested type needs.

Configuration injection

Register a type with its configuration type and the factory receives the right node of your config, already typed.

Tokens

Register the same type more than once, such as a primary and a replica database, and pick one by name.

Config references

${di.path.to.node} in JSON reuses another node, so shared settings are written once.

Singletons

An instance is created on first use and reused afterwards.

Isolated registries

Tests build their own registry instead of touching the global one.

Typed errors

Failures are errors-go errors with a code you can check.

Usage

From first service to a configured graph.

type Database struct{ DSN string }
type UserRepository struct{ DB *Database }
type UserService struct{ Repo *UserRepository }

di.Register[*Database](func(di.Context, *di.RegistryOpts) (*Database, error) {
    return &Database{DSN: "postgres://localhost/app"}, nil
})

di.Register[*UserRepository](func(ctx di.Context, _ *di.RegistryOpts) (*UserRepository, error) {
    db, err := di.Create[*Database](ctx)
    if err != nil {
        return nil, err
    }
    return &UserRepository{DB: db}, nil
})

di.Register[*UserService](func(ctx di.Context, _ *di.RegistryOpts) (*UserService, error) {
    repo, err := di.Create[*UserRepository](ctx)
    if err != nil {
        return nil, err
    }
    return &UserService{Repo: repo}, nil
})

svc, err := di.Create[*UserService](di.NewContext())
fmt.Println(svc.Repo.DB.DSN) // postgres://localhost/app
type DatabaseConfig struct {
    Host string `json:"host"`
    Port int    `json:"port"`
}

// A configuration type says how to find a child node by path.
func (c DatabaseConfig) LookupNode(path string) (any, error) {
    return di.ConfigurationNodeLookup(c, path)
}

// The factory receives its configuration as a typed argument.
func newDatabase(_ di.Context, _ *di.RegistryOpts, cfg DatabaseConfig) (*Database, error) {
    return &Database{DSN: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)}, nil
}

di.RegisterPair[*Database, DatabaseConfig](newDatabase, di.ConfigurationLookup[DatabaseConfig])
var (
    PrimaryDB = di.RegisterInjectionToken("primary")
    ReplicaDB = di.RegisterInjectionToken("replica")
)

di.RegisterPair[*Database, DatabaseConfig](newDatabase, di.ConfigurationLookup[DatabaseConfig], di.WithToken(PrimaryDB))
di.RegisterPair[*Database, DatabaseConfig](newDatabase, di.ConfigurationLookup[DatabaseConfig], di.WithToken(ReplicaDB))

// The token is also the path of the configuration node.
ctx := di.NewContext(&AppConfig{
    Primary: DatabaseConfig{Host: "db.internal", Port: 5432},
    Replica: DatabaseConfig{Host: "replica.internal", Port: 5433},
})

primary, _ := di.CreatePair[*Database, DatabaseConfig](ctx, di.WithToken(PrimaryDB))
replica, _ := di.CreatePair[*Database, DatabaseConfig](ctx, di.WithToken(ReplicaDB))

fmt.Println(primary.DSN) // db.internal:5432
fmt.Println(replica.DSN) // replica.internal:5433
// config.json
{
  "defaults": { "host": "db.internal", "port": 5432 },
  "primary": "${di.defaults}",
  "replica": { "host": "replica.internal", "port": 5433 }
}

// Resolve the references while unmarshalling.
func (c *AppConfig) UnmarshalJSON(b []byte) error {
    type plain AppConfig
    return di.UnmarshalJSONWithDIResolution(b, (*plain)(c))
}

var cfg AppConfig
err := json.Unmarshal(raw, &cfg)
// cfg.Primary == DatabaseConfig{Host: "db.internal", Port: 5432}
// A registry of its own keeps the test independent of the global one.
reg := di.NewRegistry()

di.Register[*Database](func(di.Context, *di.RegistryOpts) (*Database, error) {
    return &Database{DSN: "memory"}, nil
}, di.WithRegistry(reg))

db, err := di.Create[*Database](di.NewContext(), di.WithRegistry(reg))
How it compares

Where di-go sits next to dig, fx and wire.

The other tools are good at what they do. This is the trade di-go makes.

di-godig / fxwire
How a dependency is resolveda generic call, Create[T], inside your factoryreflection over constructor parametersgenerated Go code
Build stepnonenonecode generation
Missing dependency foundat run time, with the path through the graphat run timeat compile time
Several instances of one typetokensname tagsdistinct types
Configuration injectionbuilt inbring your ownbring your own

If you want missing dependencies caught by the compiler, wire is the stricter choice. di-go keeps the wiring in plain functions and adds configuration on top.

Open source at Pixie

One of a set that works together.

These libraries run in our own services every day. Use one, or all of them.