go 依赖注入 简单 例子

前端之家收集整理的这篇文章主要介绍了go 依赖注入 简单 例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
go 依赖注入

利用库 github.com/facebookgo/inject

例子

package main

import (
    "fmt"
    "github.com/facebookgo/inject"
)

type DBEngine struct {
    Name string
}

type UserDB struct {
    Db *DBEngine `inject:""`
}

type UserService struct {
    Db *UserDB `inject:""`
}

type App struct {
    Name string
    User *UserService `inject:""`
}

func (a *App) Create() string {
    return "create app,in db name:" + a.User.Db.Db.Name+" app name :"+ a.Name
}

type Object struct {
    App *App
}

func Init() *Object {
    db := DBEngine{Name: "db1"}
    var g inject.Graph
    app := App{Name: "go-app"}

    _ = g.Provide(
        &inject.Object{Value: &app},&inject.Object{Value: &db},)
    _ = g.Populate()
    return &Object{
        App: &app,}

}

func main() {
    obj := Init()
    fmt.Println(obj.App.Create())
}

打印结果

create app,in db name:db1 app name :go-app

猜你在找的设计模式相关文章