Register, resolve, and close services
Register values and factories, control when services are built, and release resources.
Register values and factories
Create a container with New. Pass an existing configuration value to Container.Supply and register other services with Container.Provide. Factories receive the container and use Container.Resolve to look up their dependencies.
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
})Resolve services
The container reuses a successfully constructed service. If a factory returns an error, the next resolution can retry. The example uses Container.MustResolve to surface failures at startup. Use Container.Resolve when the caller needs to handle the error.
// 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)Close resources
Call Container.Close at shutdown. It supports ioc's Closer and Go's io.Closer. The container closes resources in reverse construction order, so the repository closes before the connection it depends on. The example checks and reports shutdown errors.
// 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)
}