go 的 wire 依赖注入

首先安装 wire 工具

go install github.com/google/wire/cmd/wire@latest

go 文件

package main

import (
	"fmt"

	"github.com/google/wire"
)

var DbSet = wire.NewSet(NewDb, NewDao)

type Db struct {
	connect string
}

type Dao struct {
	DbObj Db
}

type Service struct {
	DaoObj Dao
}

func NewDb(conn string) Db {
	return Db{
		connect: conn,
	}
}

func NewDao(d Db) Dao {
	return Dao{
		DbObj: d,
	}
}

func NewService(dao Dao) Service {
	return Service{
		DaoObj: dao,
	}
}

func (s Service) Start() {
	fmt.Printf("服务器启动成功 %s\n", s.DaoObj.DbObj.connect)
}

func main() {
	db := NewDb("mysql 连接成功")
	dao := NewDao(db)
	s := NewService(dao)
	s.Start()
}

wire 文件

package main

import "github.com/google/wire"

func InitService(conn string) Service {
	panic(wire.Build(DbSet, NewService))
}

执行 wire 命令,生成新文件。

posted @ 2022-12-11 05:47  沧海一声笑rush  阅读(122)  评论(0编辑  收藏  举报