使用指南
类型化键与健康检查
区分同类型实例,检查已经构建的服务,诊断依赖循环和类型错误。
区分主副实例
主缓存与副本缓存类型相同。用两个 Key 为它们命名,使用 Key.Supply 注册现成服务,使用 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})检查健康状态
Container.Check 调用已构建服务所实现的 Checker,按名称返回结果。示例中主实例正常,副本返回连接丢失的错误。
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)
}诊断注册错误
用 Key.Provide 注册的工厂可以形成依赖链。同一条解析链检测到循环时返回 ErrCycle,以不一致的类型读取同名服务时返回 ErrTypeMismatch。保持依赖图无环,避免多个 goroutine 同时进入不同的循环分支后相互等待。
// 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)