OpenMix: OpenMix.org
Mix XDI
DI and IoC containers
DI, IoC container
Overview
A library for creating objects and handling object dependencies, which can achieve unified management of dependencies, global object management, dynamic configuration refresh, etc.
Github
- github.com/mix-go/xdi
Installation
go get github.com/mix-go/xdi
Copy the code
Quick start
Instantiate a singleton through a dependency configuration
package main
import (
"github.com/mix-go/xdi"
)
type Foo struct{}func init(a) {
obj := &xdi.Object{
Name: "foo",
New: func(a) (interface{}, error) {
i := &Foo{}
return i, nil}},iferr := xdi.Provide(obj); err ! =nil {
panic(err)
}
}
func main(a) {
var foo *Foo
if err := xdi.Populate("foo", &foo); err ! =nil {
panic(err)
}
// use foo
}
Copy the code
Reference
A dependency configuration that references another instance of a dependency configuration
package main
import (
"github.com/mix-go/xdi"
)
type Foo struct {
Bar *Bar
}
type Bar struct{}func init(a) {
objs := []*xdi.Object{
{
Name: "foo",
New: func(a) (interface{}, error) {
// reference bar
var bar *Bar
if err := xdi.Populate("bar", &bar); err ! =nil {
return nil, err
}
i := &Foo{
Bar: bar,
}
return i, nil
},
},
{
Name: "bar",
New: func(a) (interface{}, error) {
i := &Bar{}
return i, nil
},
NewEverytime: true,}}iferr := xdi.Provide(objs...) ; err ! =nil {
panic(err)
}
}
func main(a) {
var foo *Foo
if err := xdi.Populate("foo", &foo); err ! =nil {
panic(err)
}
// use foo
}
Copy the code
Refresh singleton
When configuration information changes during program execution, Refresh() can Refresh instances of singletons to switch to the new configuration, typically used in microservice configuration centers.
obj, err := xdi.Container().Object("foo")
iferr ! =nil {
panic(err)
}
iferr := obj.Refresh(); err ! =nil {
panic(err)
}
Copy the code
License
Apache License Version 2.0, www.apache.org/licenses/