美文网首页
golang 依赖注入

golang 依赖注入

作者: 杜子龙 | 来源:发表于2019-02-23 17:25 被阅读0次

    使用facebook的三方库:https://github.com/facebookgo/inject

    type C struct{
        B  *B  `inject:""`
    }
    type B struct{
        A   *A  `inject:""`//这里会根据注入对象的Name字段有选择的进行注入
    }
    type A struct{
        Name    string
    }
    var injectGraph inject.Graph
    func main() {
        a := A{
            Name: "hello",
        }
        a2 := A{
            Name: "hello2",
        }
        c := C{}
        err := injectGraph.Provide(//对象提供者
            &inject.Object{Value: &a},
            &inject.Object{Name: "这里可以给对象一个自定义命名", Value: &a2},
            &inject.Object{Value: &c},//这个也需要
        )
        if err != nil{}
        err = injectGraph.Populate()//填充对象到使用了inject标签的结构体字段中
        if err != nil{}
        fmt.Println(c.B.A.Name)
    }
    // 通过injectGraph.Objects()可以获取所有设置了Name的待填充对象
    func GetObject(name string) interface{} {
        for _, o := range injectGraph.Objects() {
            if o.Name == name {
                return o.Value
            }
        }
        return nil
    }
    

    相关文章

      网友评论

          本文标题:golang 依赖注入

          本文链接:https://www.haomeiwen.com/subject/delpyqtx.html