简化对象创建流程
一般我们的 go web 代码中,会有如此的依赖关系:controller 依赖 service,service 又依赖 repository,这样 controller 一多,我们创建其的代码又多又繁琐。
好在有了 wire,我们可以利用代码生成的方式,来简化这种依赖关系的创建。
示例代码中,People 也是依赖了 Mouth、Hand,它们又向下又依赖,我们最终只需要调用 InitPeople
即可。
package main
import "fmt"
type Meta struct {
}
func NewMeta() Meta {
return Meta{}
}
type Message struct {
msg string
r Meta
}
func NewMessage(msg string, r Meta) Message {
return Message{
msg: msg,
r: r,
}
}
type Mouth struct {
Message Message
}
func NewMouth(m Message) Mouth {
return Mouth{Message: m}
}
type Hand struct {
Message Message
}
func NewHand(m Message) Hand {
return Hand{Message: m}
}
type People struct {
Mouth Mouth
Hand Hand
}
func NewPeople(m Mouth, h Hand) People {
return People{
Mouth: m,
Hand: h,
}
}
func (p People) Hi() {
msg := p.Mouth.Message.msg
fmt.Println(msg)
}
func main() {
p := InitPeople("Hi, Wire!")
p.Hi()
}
InitPeople
来自自动生成的代码,它是通过 wire 自动生成的。
我们只需要在项目目录下创建,wire.go
文件:
//go:build wireinject
// +build wireinject
package main
import "github.com/google/wire"
func InitPeople(msg string) People {
wire.Build(NewPeople, NewMouth, NewHand, NewMessage, NewMeta)
return People{}
}
最后运行 wire
命令,就能生成 InitPeople
的代码。
生成代码如下:
// Code generated by Wire. DO NOT EDIT.
//go:generate go run github.com/google/wire/cmd/wire
//go:build !wireinject
// +build !wireinject
package main
// Injectors from wire.go:
func InitPeople(msg string) People {
meta := NewMeta()
message := NewMessage(msg, meta)
mouth := NewMouth(message)
hand := NewHand(message)
people := NewPeople(mouth, hand)
return people
}