fix: 移除 modular 包的自动注入,优化 modular.Service 接口说明

This commit is contained in:
kercylan98 2024-01-31 12:09:20 +08:00
parent ad4777a379
commit d531939903
6 changed files with 17 additions and 13 deletions

View File

@ -1,5 +1,7 @@
package expose
var AttackExpose Attack
type Attack interface {
Name() string
}

View File

@ -1,5 +1,7 @@
package expose
var LoginExpose Login
type Login interface {
Name() string
}

View File

@ -11,15 +11,16 @@ type Service struct {
}
func (a *Service) OnInit() {
expose.AttackExpose = a
a.name = "attack"
}
func (a *Service) OnPreload() {
fmt.Println(a.name, "call", a.Login.Name())
a.Login = expose.LoginExpose
}
func (a *Service) OnMount() {
fmt.Println("attack service mounted, call", a.Login.Name(), "service")
}
func (a *Service) Name() string {

View File

@ -11,15 +11,16 @@ type Service struct {
}
func (l *Service) OnInit() {
expose.LoginExpose = l
l.name = "login"
}
func (l *Service) OnPreload() {
fmt.Println(l.name, "call", l.Attack.Name())
l.Attack = expose.AttackExpose
}
func (l *Service) OnMount() {
fmt.Println("attack service mounted, call", l.Attack.Name(), "service")
}
func (l *Service) Name() string {

View File

@ -47,15 +47,6 @@ func Run() {
// OnPreload
for i := 0; i < len(m.services); i++ {
s := m.services[i]
for f := 0; f < s.vof.Elem().NumField(); f++ {
field := s.vof.Elem().Field(f)
for _, v := range tvm {
if v.Type().AssignableTo(field.Type()) {
field.Set(v)
break
}
}
}
s.instance.OnPreload()
log.Info(fmt.Sprintf("service %s preloaded", s.name))
}

View File

@ -4,6 +4,13 @@ import "reflect"
// Service 模块化服务接口,所有的服务均需要实现该接口,在服务的生命周期内发生任何错误均应通过 panic 阻止服务继续运行
// - 生命周期示例: OnInit -> OnPreload -> OnMount
//
// 在 Golang 中,包与包之间互相引用会导致循环依赖,因此在模块化应用程序中,所有的服务均不应该直接引用其他服务。
//
// 服务应该在 OnInit 阶段将不依赖其他服务的内容初始化完成,并且如果服务需要暴露给其他服务调用,那么也应该在 OnInit 阶段完成对外暴露。
// - 暴露方式可参考 modular/example
//
// 在 OnPreload 阶段,服务应该完成对其依赖服务的依赖注入,最终在 OnMount 阶段完成对服务功能的定义、路由的声明等。
type Service interface {
// OnInit 服务初始化阶段,该阶段不应该依赖其他任何服务
OnInit()