di
Package di provides a reflection-based dependency injection toolkit.
Feature
- Support value service, shared service and local service.
- Easily extend existing injector.
- Automatic cleanup.
Usage
import (
"fmt"
"io"
"strconv"
"strings"
"gitlab.com/erdian718/di"
)
func main() {
inj, err := di.New(nil).
Value(888, nil).
Share(func(v int) string {
return strconv.Itoa(v)
}, nil).
Local(func(s string) *strings.Reader {
return strings.NewReader(s)
}, (*io.Reader)(nil)).
Build()
if err != nil {
panic(err)
}
defer inj.Close()
_, err = inj.Invoke(func(r io.Reader) error {
data, err := io.ReadAll(r)
if err != nil {
return err
}
fmt.Printf("%s\n", data)
return nil
})
if err != nil {
panic(err)
}
}
Note
- The injector itself is not goroutine safe, but each goroutine can clone an injector.