Typed keys and health checks
Distinguish instances of the same type, check built services, and diagnose cycles or type mismatches.
Distinguish primary and replica instances
The primary and replica caches have the same type. Use two Key values to name them. Register existing services with Key.Supply and look them up with Key.Resolve.
// A Key carries its service type: Primary.Resolve returns a *Cache with no
// type assertion.
var (
Primary = ioc.Key[*Cache]("cache.primary")
Replica = ioc.Key[*Cache]("cache.replica")
)Primary.Supply(c, &Cache{addr: "10.0.0.1:6379", isConnected: true})
Replica.Supply(c, &Cache{addr: "10.0.0.2:6379", isConnected: false})Check service health
Container.Check calls the Checker implemented by each constructed service and returns results by name. In the example, the primary instance is healthy and the replica reports a lost connection.
health := c.Check(context.Background())
for _, name := range slices.Sorted(maps.Keys(health)) {
status := "ok"
if err := health[name]; err != nil {
status = err.Error()
}
fmt.Printf("%s: %s\n", name, status)
}Diagnose registration errors
Factories registered with Key.Provide can form dependency chains. A cycle in a single resolution chain returns ErrCycle. Reading a named service with an incompatible type returns ErrTypeMismatch. Keep the dependency graph acyclic so goroutines cannot enter different branches of a cycle and wait on each other.
// A dependency cycle is detected instead of deadlocking or overflowing
// the stack.
a, b := ioc.Key[string]("a"), ioc.Key[string]("b")
a.Provide(c, b.Resolve)
b.Provide(c, a.Resolve)
_, err := a.Resolve(c)
fmt.Println(errors.Is(err, ioc.ErrCycle), err)
// Resolving a name with a key of another type reports a type mismatch.
_, err = ioc.Key[string]("cache.primary").Resolve(c)
fmt.Println(errors.Is(err, ioc.ErrTypeMismatch), err)