Dependency injection using Generics.
- Provide dependencies in a natural and type-safe way
- Register dependencies with other dependencies (e.g. register a controller with the router)
- Swap out dependencies during testing
- Middleware support
- Unmarshal dependencies into a struct
go get github.com/livebud/di
In the following example, we load the logger which loads the environment:
type Env struct {
DatabaseURL string
}
func provideEnv(in di.Injector) (*Env, error) {
return &Env{
DatabaseURL: "postgres://localhost:5432/db",
}, nil
}
type Log struct {
env *Env
}
func provideLog(in di.Injector) (*Log, error) {
env, err := di.Load[*Env](in)
if err != nil {
return nil, err
}
return &Log{env}, nil
}
func main() {
in := di.New()
di.Provide(in, provideEnv)
di.Provide(in, provideLog)
log, err := di.Load[*Log](in)
fmt.Println(log.env.DatabaseURL)
}
- Matt Mueller (@mattmueller)
MIT