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.
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.
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.
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.
The factory is ordinary Go. You can read it, step through it and set a breakpoint in it.
Create[*API](ctx) returns a *API. There are no casts and no interface{} at the call site.
A failed creation names the missing dependency and the path through the graph that led to it.
Registration order does not matter. Nothing is built until Create is called, and then only what the requested type needs.
Register a type with its configuration type and the factory receives the right node of your config, already typed.
Register the same type more than once, such as a primary and a replica database, and pick one by name.
${di.path.to.node} in JSON reuses another node, so shared settings are written once.
An instance is created on first use and reused afterwards.
Tests build their own registry instead of touching the global one.
Failures are errors-go errors with a code you can check.
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/apptype 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))The other tools are good at what they do. This is the trade di-go makes.
| di-go | dig / fx | wire | |
|---|---|---|---|
| How a dependency is resolved | a generic call, Create[T], inside your factory | reflection over constructor parameters | generated Go code |
| Build step | none | none | code generation |
| Missing dependency found | at run time, with the path through the graph | at run time | at compile time |
| Several instances of one type | tokens | name tags | distinct types |
| Configuration injection | built in | bring your own | bring 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.
These libraries run in our own services every day. Use one, or all of them.