https://github.com/gookit/di
Lightweight dependency injection container implements by Go
https://github.com/gookit/di
container dependency-injection
Last synced: 23 days ago
JSON representation
Lightweight dependency injection container implements by Go
- Host: GitHub
- URL: https://github.com/gookit/di
- Owner: gookit
- License: mit
- Created: 2018-12-06T05:49:36.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2018-12-06T16:09:10.000Z (over 6 years ago)
- Last Synced: 2025-03-27T20:41:03.589Z (about 1 month ago)
- Topics: container, dependency-injection
- Language: Go
- Homepage:
- Size: 20.5 KB
- Stars: 4
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-go - DI - lightweight dependency injection container. (Dependency Injection)
README
# DI
[](https://godoc.org/github.com/gookit/di)
[](https://travis-ci.org/gookit/di)
[](https://coveralls.io/github/gookit/di?branch=master)
[](https://goreportcard.com/report/github.com/gookit/di)> **[中文说明](README_cn.md)**
Lightweight dependency injection container implements by Go.
## GoDoc
- [godoc for gopkg](https://godoc.org/gopkg.in/gookit/di.v1)
- [godoc for github](https://godoc.org/github.com/gookit/di)## Install
```bash
go get github.com/gookit/di
```## Usage
```go
package mainimport (
"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)
}
```## API Methods
- `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)`## Refer
- https://github.com/sarulabs/di
- https://github.com/codegangsta/inject
- https://github.com/go-ozzo/ozzo-di
- https://github.com/xialeistudio/di-demo## License
**[MIT](LICENSE)**