推荐依赖注入库: go-container
go-container 是使用go的反射实现的轻量级的依赖注入库,使用简单
下载
go get -u github.com/deatil/go-container
示例
package main
import (
"fmt"
"github.com/deatil/go-container/container"
)
type testBind struct {}
func (t *testBind) Data() string {
return "testBind data"
}
func UseFunc(a string) {}
// 更多示例可以查看测试文件
func main() {
// Bind func
di := container.DI()
di.Bind("testBind", func() *testBind {
return &testBind{}
})
tb := di.Get("testBind")
tb2, _ := tb.(*testBind)
fmt.Printf("output: %s", tb2.Data())
// output: testBind data
}
同时支持调用函数和结构体方法
调用函数
res := di.Call(UseFunc, []any{"inin"})
调用结构体方法
res := di.Call([]any{&testBind{}, "Data"}, nil)
项目地址
github.com/deatil/go-container
本作品采用《CC 协议》,转载必须注明作者和本文链接
这个早就标准化了 。。。
github.com/google/wire