Lightweight dependency injection container implements by Go.
go get github.com/gookit/di
package main
import (
"github.com/gookit/di"
)
func main() {
box := di.New("my-services")
// add a simple value
box.Set("service1", "val1")
// register a callback func.
box.Set("service2", func() (interface, error) {
return &MyApp{}, nil
})
// register a factory func.
box.Set("service3", func() (interface, error) {
return &MyObject{}, nil
}, true)
// get
v1 := box.Get("service1") // "val1"
// is a singleton value. Notice: v2 == v3
v2 := box.Get("service2").(*MyApp)
v3 := box.Get("service2").(*MyApp)
// is factory func. Notice: v4 != v5
v4 := box.Get("service3").(*MyObject)
v5 := box.Get("service3").(*MyObject)
}
func (c *Container) Set(name string, val interface{}, isFactory ...bool) *Container
func (c *Container) Get(name string) interface{}
func (c *Container) SafeGet(name string) (val interface{}, err error)
func (c *Container) Inject(ptr interface{}) (err error)