luminyra
使用指南

注册、解析与关闭

在容器中登记现成值和工厂,控制构建时机并释放资源。

注册值和工厂

用 New 创建容器,把已经加载的配置传给 Container.Supply。用 Container.Provide 注册其余服务,工厂接收容器并调用 Container.Resolve 获取自己的依赖。

ioc/examples/basic/main.go
c := ioc.New()

// Ready values are supplied directly.
c.Supply(&Config{DSN: "postgres://localhost/app"})

// Other services are registered as providers. They are built on first use
// and then reused; the *ioc.Container a provider receives resolves its own
// dependencies.
c.Provide(func(c *ioc.Container) (*DB, error) {
	cfg, err := c.Resolve[*Config]()
	if err != nil {
		return nil, err
	}
	fmt.Println("connecting to database:", cfg.DSN)
	return &DB{dsn: cfg.DSN}, nil
})
c.Provide(func(c *ioc.Container) (*UserRepo, error) {
	db, err := c.Resolve[*DB]()
	if err != nil {
		return nil, err
	}
	return &UserRepo{db: db}, nil
})
在 GitHub 查看

解析服务

解析成功后,容器会复用构建结果。工厂如果返回错误,下次解析可以重试。在启动期希望立即暴露错误时,示例使用 Container.MustResolve。需要自行处理失败时,优先使用返回错误的 Container.Resolve。

ioc/examples/basic/main.go
// Resolve is a generic method: the requested type goes in brackets.
repo := c.MustResolve[*UserRepo]()
again := c.MustResolve[*UserRepo]()
fmt.Println("same instance:", repo == again)
在 GitHub 查看

关闭资源

在服务退出时调用 Container.Close。支持的关闭方式包括 ioc 的 Closer 和 Go 的 io.Closer。容器按构建逆序执行关闭,因此仓库先于它依赖的连接释放。示例检查并报告关闭错误。

ioc/examples/basic/main.go
// Services are closed in reverse build order, through ioc.Closer,
// Shutdown(ctx) or io.Closer.
if err := c.Close(context.Background()); err != nil {
	fmt.Println("close failed:", err)
}
在 GitHub 查看

本页目录