Skip to content
v2See what changed

Dependency injection, typed

Register services under typed keys and get them back as their own types, with no type assertions or reflection. Reads never wait for a lock.

go get github.com/vardius/gocontainer/v2
main.go
// A key names a service and fixes its type.
// Declare it once and share it.
var (
DB = gocontainer.NewKey[*sql.DB]("db")
Users = gocontainer.NewKey[UserStore]("users")
)
  • 22×faster than v1's Invoke: Get returns the type, with no reflection
  • 474×faster than v1 to read from 16 goroutines at once
  • 3.6 nsto get a service: a map lookup with no lock
  • 0allocations to Get, MustGet or check with Has

Features

Typed keys

A Key[T] names a service and fixes its type. Register takes a T and Get returns one: no interface{}, no type assertions.

Checked when you build

A value of the wrong type under a key doesn’t compile. A concrete type goes in under an interface key as it is.

Reads never wait

Get, MustGet and Has take no lock and allocate nothing, so goroutines reading at once don’t slow each other down.

No globals

The zero Container is ready to use, and nothing runs in init(). Declare a container where you wire your services.

Easy to fake

A key works with any container. A test registers a fake under the same key in a container of its own.

Small API

One type to hold services, one to name them, five methods. No dependencies beyond the standard library.

Performance

v2 reads from a map it never changes once published, so a read is an atomic load and a lookup, with no lock. The calls that replace v1’s reflection-based Invoke are about twenty times faster. Writes copy the map, so they cost more than v1’s.

Time per read, lower is better
Show as a table
Time per read: time and allocations, v1 against v2
Scenariov1v2
Get5.8 ns0 allocs3.6 ns0 allocs
Get, not registered4.8 ns0 allocs3.3 ns0 allocs
MustGet6.4 ns0 allocs3.5 ns0 allocs
Has6.2 ns0 allocs3.4 ns0 allocs

Apple M4 Max, Go 1.27.0, median of 5 runs.

Upgrading

String ids become typed keys, and Invoke gives way to Get and MustGet, which return the type you want. The global container is gone: you declare your own.

v1
gocontainer.Register("db", openDB())
gocontainer.MustInvoke("db",
func(db *sql.DB) {
// use db
},
)
v2
var DB = gocontainer.NewKey[*sql.DB]("db")
var c gocontainer.Container
DB.Register(&c, openDB())
db := DB.MustGet(&c) // use db

Wire your first services in five minutes

Install the module, declare a key for each service, and register them in a container. The guide walks through it.