1 安装wire
1.1 通过命令直接安装
go install github.com/google/wire/cmd/wire@latest
1.2 通过go get方式安装
go get github.com/google/wire/cmd/wire
进入目录编译
cd C:\Users\leell\go\pkg\mod\github.com\google\wire@v0.6.0\cmd\wire
go build
然后将wire.exe移动到 C:\Users\leell\go\bin目录下
具体目录通过go env进行查看
C:\Users\leell\go>go env
set GO111MODULE=on
set GOARCH=amd64
set GOBIN=C:\Users\leell\go\bin
2 配置业务代码
我没有按照beego的默认目录,而是通过自定义app包名进行业务模块化
2.1 分类模块
app/category/category_controller.go
type Controller struct {controller.BaseControllerservice *Service
}func NewController(service *Service) *Controller {return &Controller{service: service}
}
app/category/category_service.go
type Service struct {dao *Dao
}func NewService(dao *Dao) *Service {return &Service{dao}
}
app/category/category_dao.go
type Dao struct {ormer orm.Ormer
}func NewDao(ormer orm.Ormer) *Dao {return &Dao{ormer}
}
app/category/fx.go
package categoryimport ("github.com/beego/beego/v2/server/web""github.com/google/wire"
)type FxRouter struct {controller *Controller
}func NewAppRouter(controller *Controller) *FxRouter {return &FxRouter{controller}
}
func (r *FxRouter) Router(namespace *web.Namespace) {namespace.Get("/category", r.controller.GetAll)namespace.Get("/category/:id", r.controller.GetOne)namespace.Post("/category", r.controller.Post)namespace.Put("/category/:id", r.controller.Put)namespace.Delete("/category/:id", r.controller.Delete)
}var Set = wire.NewSet(NewController, NewService, NewDao, NewAppRouter)
app/fx.go:将分类模块引入app/fx.go中并且等待注册路由
package appimport ("github.com/beego/beego/v2/server/web""github.com/google/wire""zhiqu/app/category""zhiqu/app/login""zhiqu/app/user"
)type FxRouter struct {categoryFxRouter *category.FxRouterloginFxRouter *login.FxRouteruserFxRouter *user.FxRouter
}func NewAppRouter(categoryFxRouter *category.FxRouter,loginFxRouter *login.FxRouter,userFxRouter *user.FxRouter) *FxRouter {return &FxRouter{categoryFxRouter, loginFxRouter, userFxRouter}
}
func (r *FxRouter) Router(namespace *web.Namespace) {r.categoryFxRouter.Router(namespace)r.loginFxRouter.Router(namespace)r.userFxRouter.Router(namespace)
}var Set = wire.NewSet(NewAppRouter, category.Set, login.Set, user.Set)
2.2 项目wire定义总提供者provider
infrastructure/database/pgsql/db.go
package pgsqlimport ("fmt""github.com/beego/beego/v2/client/orm"beego "github.com/beego/beego/v2/server/web"_ "github.com/lib/pq"
)func init() {pgsqlUser, _ := beego.AppConfig.String("pgsqlUser")pgsqlPass, _ := beego.AppConfig.String("pgsqlPass")pgsqlDbName, _ := beego.AppConfig.String("pgsqlDbName")pgsqlHost, _ := beego.AppConfig.String("pgsqlHost")pgsqlPort, _ := beego.AppConfig.String("pgsqlPort")pgsqlSslMode, _ := beego.AppConfig.String("pgsqlSslMode")// 注册驱动err := orm.RegisterDriver("postgres", orm.DRPostgres)if err != nil {panic(err)}// 设置默认数据库err = orm.RegisterDataBase("default", "postgres", fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=%s", pgsqlUser, pgsqlPass, pgsqlDbName, pgsqlHost, pgsqlPort, pgsqlSslMode))if err != nil {panic(err)}
}
func NewPgsqlOrm() orm.Ormer {ormer := orm.NewOrm()return ormer
}
provider/provider.go
var Set = wire.NewSet(NewBeanFactory, pgsql.NewPgsqlOrm, app.Set)
2.3 给项目一个bean工厂
这点有点像spring的beanfactory,这里主要是:
(1)解决beego路由一开始执行init能够得到所有controller的实例
(2)go项目中存在recycle的循环依赖,这里就可以用beanFactory做一个中间过度
package providerimport ("github.com/beego/beego/v2/core/logs""sync""zhiqu/app"
)var (AppBeanFactory *BeanFactoryonce sync.OnceBeeLog *logs.BeeLogger
)type BeanFactory struct {AppFxRouter *app.FxRouter
}func init() {BeeLog = logs.NewLogger()err := BeeLog.SetLogger(logs.AdapterConsole)if err != nil {return}
}
func NewBeanFactory(appFxRouter *app.FxRouter) *BeanFactory {once.Do(func() {AppBeanFactory = &BeanFactory{AppFxRouter: appFxRouter,}})return AppBeanFactory
}
3 wire配置代码及生成gen代码
wire/wire.go
//go:build wireinject
// +build wireinjectpackage wireimport ("zhiqu/provider"
)
import "github.com/google/wire"// wire.go 初始化模块
func NewApp() (*provider.BeanFactory, error) {panic(wire.Build(provider.Set))
}
执行wire命令生成gen代码得到wire/wire_gen.go
wire gen wire/wire.go
生成最终代码文件内容
wire/wire_gen.go
// Code generated by Wire. DO NOT EDIT.//go:generate go run -mod=mod github.com/google/wire/cmd/wire
//go:build !wireinject
// +build !wireinjectpackage wireimport ("zhiqu/app/category""zhiqu/provider"
)// Injectors from wire.go:// wire.go 初始化模块
func NewApp() (*provider.BeanFactory, error) {categoryDao := category.NewDao()categoryService := category.NewService(categoryDao)categoryController := category.NewController(categoryService)beanFactory := provider.NewBeanFactory(categoryController)return beanFactory, nil
}
4 路由配置
routers/router.go
// Package routers 路由配置
package routersimport ("github.com/beego/beego/v2/server/web""zhiqu/wire"
)func init() {beanFactory, err := wire.NewApp()if err != nil {panic(err)}//这是一种可实现的依赖注入全自动方式ns := web.NewNamespace("/v1", func(namespace *web.Namespace) {beanFactory.AppFxRouter.Router(namespace)})web.SetStaticPath("/swagger", "swagger")web.AddNamespace(ns)
}
可以看出在路由文件中添加了wire生成的gen代码的获取的beanfactory工厂,然后将所有的单例go对象交由wire进行管理
注意:这里采用的是beego的web方式而不是beego方式,这里都是手动配置路由,不要去通过命令生成commentsRouter.go这样的路由文件
为啥不采用beego注册路由?
因为我们要想做到依赖注入,得确保controller、service、dao这些是单例,而beego注册的路由内部是现实每次收到请求都会通过反射技术重新构建一个controler进行处理。
正式因为最开始通过官方生成的项目配置路由注册时beego方式,而不能实现依赖注入,最终选择了gin+gorm+go.uber.org/fx的架构组合
5 查看最终结果
不过我不太推荐这种方式的依赖注入,虽然是在编译期实现了代码的生成,减少了启动通过反射来进行依赖注入的方式的时间,但是对开发人员来说多了一道工序。并且启动时间也要不了多久,而且编译器和运行期的依赖注入对接口运行是没有影响。
给大家推荐一块依赖注入框架:go.uber.org/fx
源代码:GitHub - leellun/beego-wire