经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Go语言 » 查看文章
goioc:一个使用 Go 写的简易的 ioc 框架
来源:cnblogs  作者:痴者工良  时间:2022/11/28 8:56:45  对本文有异议

goioc 介绍

goioc 是一个基于 GO 语言编写的依赖注入框架,基于反射进行编写。

  • 支持泛型;
  • 简单易用的 API;
  • 简易版本的对象生命周期管理,作用域内对象具有生命;
  • 延迟加载,在需要的时候才会实例化对象;
  • 支持结构体字段注入,多层注入;
  • 对象实例化线程安全,作用域内只会被执行一次。

下载依赖:

  1. go get -u github.com/whuanle/goioc v2.0.0

快速上手

定义接口:

  1. type IAnimal interface {
  2. Println(s string)
  3. }

实现接口:

  1. type Dog struct {
  2. }
  3. func (my Dog) Println(s string) {
  4. fmt.Println(s)
  5. }

依赖注入以及使用:

  1. // 注册容器
  2. var sc goioc.IServiceCollection = &ServiceCollection{}
  3. // 注入服务
  4. goioc.AddServiceOf[IAnimal, Dog](sc, goioc.Scope)
  5. // 构建提供器
  6. p := sc.Build()
  7. // 获取服务
  8. obj := goioc.Get[IAnimal](p)

接口介绍

IServiceCollection 是一个容器接口,通过此接口,将需要进行依赖注入的对象注册到容器中。

IServiceProvider 是一个服务提供器,当服务注册到容器后,构建一个服务提供器,IServiceProvider 可以管理服务的生命周期以及提供服务。

IDispose 接口用于声明此对象在 IServiceProvider 结束时,需要执行接口释放对象。

  1. // IDispose 释放接口
  2. type IDispose interface {
  3. // Dispose 释放资源
  4. Dispose()
  5. }

除此之外,goioc 中还定义了部分扩展函数,如泛型注入等,代码量不多,简单易用。

使用 goioc

如何使用

注入的服务有两种形式,第一种是 B:A,即 B 实现了 A,使用的时候获取 A ;第二种是注入 B,使用的时候获取 B。

  1. // 第一种
  2. AddServiceOf[A,B]()
  3. // 第二种
  4. AddService[B]()

A 可以是接口或结构体,只要 B 实现了 A 即可。

定义一个接口:

  1. type IAnimal interface {
  2. Println(s string)
  3. }

实现这个接口:

  1. type Dog struct {
  2. Id int
  3. }
  4. func (my Dog) Println(s string) {
  5. fmt.Println(s)
  6. }

当使用依赖注入框架时,我们可以将接口和实现分开,甚至放到两个模块中,可以随时替换接口的实现。

注册服务和获取服务的代码示例如下:

  1. func Demo() {
  2. sc := &ServiceCollection{}
  3. goioc.AddServiceOf[IAnimal, Dog](sc, goioc.Scope)
  4. p := sc.Build()
  5. animal := goioc.GetI[IAnimal](p)
  6. animal.Println("test")
  7. }

下面讲解编码过程。

首先创建 IServiceCollection 容器,容器中可以注册服务。

  1. sc := &ServiceCollection{}

然后通过接口注入服务:

  1. goioc.AddServiceOf[IAnimal, Dog](sc, goioc.Scope)

这个函数是泛型方法。如果不使用泛型,则注入过程麻烦得多。

注册完毕后,开始构建提供器:

  1. p := sc.Build()

然后获取服务:

  1. animal := goioc.GetI[IAnimal](p)
  2. animal.Println("test")

生命周期

goioc 中定义了三个生命周期:

  1. const (
  2. Transient ServiceLifetime = iota
  3. Scope
  4. Singleton
  5. )

Transient:瞬时模式,每次获取到的都是新的对象;

Scope:作用域模式,同一个 Provider 中获取到的是同一个对象。

Singleton:单例模式,同一个 ServiceCollection 获取到的是同一个对象,也就是所有 Provider 获取到的都是同一个对象。

如果是单例模式(Singleton),那么无论多少次 Build,对象始终是同一个:

在注册服务的时候,需要注明对象生命周期。

  1. goioc.AddServiceOf[IAnimal, Dog](sc, goioc.Scope)

生命周期为 scope 的注入,同一个 Provider 中,获取到的对象是一样的。

  1. sc := &ServiceCollection{}
  2. goioc.AddServiceOf[IAnimal, Dog](sc, goioc.Scope)
  3. p := sc.Build()
  4. // 第一次获取对象
  5. animal1 := goioc.GetI[IAnimal](p)
  6. if animal1 == nil {
  7. t.Errorf("service is nil!")
  8. }
  9. animal1.Println("test")
  10. // 第二次获取对象
  11. animal2 := goioc.GetI[IAnimal](p)
  12. if animal2 == nil {
  13. t.Errorf("service is nil!")
  14. }
  15. // animal1 和 animal2 引用了同一个对象
  16. if animal1 != animal2 {
  17. t.Errorf("animal1 != animal2")
  18. }

实例一,Scope 生命周期的对象,在同一个提供器下获取到的都是同一个对象。

  1. sc := &ServiceCollection{}
  2. goioc.AddServiceHandlerOf[IAnimal, Dog](sc, goioc.Scope, func(provider goioc.IServiceProvider) interface{} {
  3. return &Dog{
  4. Id: 3,
  5. }
  6. })
  7. p := sc.Build()
  8. // 第一次获取
  9. a := goioc.GetI[IAnimal](p)
  10. if v := a.(*Dog); v == nil {
  11. t.Errorf("service is nil!")
  12. }
  13. v := a.(*Dog)
  14. if v.Id != 2 {
  15. t.Errorf("Life cycle error")
  16. }
  17. v.Id = 3
  18. // 第二次获取
  19. aa := goioc.GetI[IAnimal](p)
  20. v = aa.(*Dog)
  21. if v.Id != 3 {
  22. t.Errorf("Life cycle error")
  23. }
  24. // 重新构建的 scope,不是同一个对象
  25. pp := sc.Build()
  26. aaa := goioc.GetI[IAnimal](pp)
  27. v = aaa.(*Dog)
  28. if v.Id != 2 {
  29. t.Errorf("Life cycle error")
  30. }

实例二, ServiceCollection 构建的提供器,单例模式下获取到的都是同一个对象。

  1. sc := &ServiceCollection{}
  2. goioc.AddServiceHandler[Dog](sc, goioc.Singleton, func(provider goioc.IServiceProvider) interface{} {
  3. return &Dog{
  4. Id: 2,
  5. }
  6. })
  7. p := sc.Build()
  8. b := goioc.GetS[Dog](p)
  9. if b.Id != 2 {
  10. t.Errorf("Life cycle error")
  11. }
  12. b.Id = 3
  13. bb := goioc.GetS[Dog](p)
  14. if b.Id != bb.Id {
  15. t.Errorf("Life cycle error")
  16. }
  17. ppp := sc.Build()
  18. bbb := goioc.GetS[Dog](ppp)
  19. if b.Id != bbb.Id {
  20. t.Errorf("Life cycle error")
  21. }

实例化

由开发者决定如何实例化一个对象。

主要由注册形式决定,有四个泛型函数实现注册服务:

  1. // AddService 注册对象
  2. func AddService[T any](con IServiceCollection, lifetime ServiceLifetime)
  3. // AddServiceHandler 注册对象,并自定义如何初始化实例
  4. func AddServiceHandler[T any](con IServiceCollection, lifetime ServiceLifetime, f func(provider IServiceProvider) interface{})
  5. // AddServiceOf 注册对象,注册接口或父类型及其实现,serviceType 必须实现了 baseType
  6. func AddServiceOf[I any, T any](con IServiceCollection, lifetime ServiceLifetime)
  7. // AddServiceHandlerOf 注册对象,注册接口或父类型及其实现,serviceType 必须实现了 baseType,并自定义如何初始化实例
  8. func AddServiceHandlerOf[I any, T any](con IServiceCollection, lifetime ServiceLifetime, f func(provider IServiceProvider) interface{})

AddService[T any]:只注册可被实例化的对象:

  1. AddService[T any]
  1. goioc.AddService[Dog](sc, goioc.Scope)

AddServiceHandler 注册一个接口或结构体,自定义实例化。

func(provider goioc.IServiceProvider) interface{} 函数会在实例化对象时执行。

  1. goioc.AddServiceHandler[Dog](sc, goioc.Scope, func(provider goioc.IServiceProvider) interface{} {
  2. return &Dog{
  3. Id: 1,
  4. }
  5. })

在实例化时,如果这个对象还依赖其他服务,则可以通过 goioc.IServiceProvider 来获取其他依赖。

例如下面示例中,一个依赖另一个对象,可以自定义实例化函数,从容器中取出其他依赖对象,然后构建一个新的对象。

  1. goioc.AddServiceHandler[Dog](sc, goioc.Scope, func(provider goioc.IServiceProvider) interface{} {
  2. a := goioc.GetI[IA](provider)
  3. return &Dog{
  4. Id: 1,
  5. A: a,
  6. }
  7. })
  1. goioc.AddServiceHandler[Dog](sc, goioc.Scope, func(provider goioc.IServiceProvider) interface{} {
  2. config := goioc.GetI[Config](provider)
  3. if config.Enable == false
  4. return &Dog{
  5. Id: 1,
  6. }
  7. })

获取对象

前面提到,我们可以注入 [A,B],或者 [B]

那么获取的时候就有三种函数:

  1. // Get 获取对象
  2. func Get[T any](provider IServiceProvider) interface{}
  3. // GetI 根据接口获取对象
  4. func GetI[T interface{}](provider IServiceProvider) T
  5. // GetS 根据结构体获取对象
  6. func GetS[T interface{} | struct{}](provider IServiceProvider) *T

Get[T any] 获取接口或结构体,返回 interface{}

GetI[T interface{}] 获取的是一个接口实例。

GetS[T interface{} | struct{}] 获取的是一个结构体实例。

以上三种方式,返回的都是对象的引用,即指针。

  1. sc := &ServiceCollection{}
  2. goioc.AddService[Dog](sc, goioc.Scope)
  3. goioc.AddServiceOf[IAnimal, Dog](sc, goioc.Scope)
  4. p := sc.Build()
  5. a := goioc.Get[IAnimal](p)
  6. b := goioc.Get[Dog](p)
  7. c := goioc.GetI[IAnimal](p)
  8. d := goioc.GetS[Dog](p)

结构体字段依赖注入

结构体中的字段,可以自动注入和转换实例。

如结构体 Animal 的定义,其使用了其它结构体,goioc 可以自动注入 Animal 对应字段,要被注入的字段必须是接口或者结构体。

  1. // 结构体中包含了其它对象
  2. type Animal struct {
  3. Dog IAnimal `ioc:"true"`
  4. }

要对需要自动注入的字段设置 tag 中包含ioc:"true" 才会生效。

示例代码:

  1. sc := &ServiceCollection{}
  2. goioc.AddServiceHandlerOf[IAnimal, Dog](sc, goioc.Scope, func(provider goioc.IServiceProvider) interface{} {
  3. return &Dog{
  4. Id: 666,
  5. }
  6. })
  7. goioc.AddService[Animal](sc, goioc.Scope)
  8. p := sc.Build()
  9. a := goioc.GetS[Animal](p)
  10. if dog := a.Dog.(*Dog); dog.Id != 666 {
  11. t.Errorf("service is nil!")
  12. }

goioc 可以自动给你的结构体字段进行自动依赖注入。

注意,goioc 的字段注入转换逻辑是这样的。

如果 obj 要转换为接口,则是使用:

  1. animal := (*obj).(IAnimal)

如果 obj 要转换为结构体,则是:

  1. animal := (*obj).(*Animal)

Dispose 接口

反射形式使用 goioc

如何使用

goioc 的原理是反射,ioc 使用了大量的反射机制实现依赖注入,但是因为 Go 的反射比较难用,导致操作十分麻烦,因此使用泛型包装一层可以降低使用难度。

当然,也可以直接使用原生的反射方式进行依赖注入。

首先反射通过反射获取 reflect.Type

  1. // 获取 reflect.Type
  2. imy := reflect.TypeOf((*IAnimal)(nil)).Elem()
  3. my := reflect.TypeOf((*Dog)(nil)).Elem()

依赖注入:

  1. // 创建容器
  2. sc := &ServiceCollection{}
  3. // 注入服务,生命周期为 scoped
  4. sc.AddServiceOf(goioc.Scope, imy, my)
  5. // 构建服务 Provider
  6. serviceProvider := sc.Build()

获取服务以及进行类型转换:

  1. // 获取对象
  2. // *interface{} = &Dog{},因此需要处理指针
  3. obj, err := serviceProvider.GetService(imy)
  4. animal := (*obj).(IAnimal)

示例:

  1. imy := reflect.TypeOf((*IAnimal)(nil)).Elem()
  2. my := reflect.TypeOf((*Dog)(nil)).Elem()
  3. var sc IServiceCollection = &ServiceCollection{}
  4. sc.AddServiceOf(goioc.Scope,imy, my)
  5. p := sc.Build()
  6. // 获取对象
  7. // *interface{} = &Dog{},因此需要处理指针
  8. obj1, _ := p.GetService(imy)
  9. obj2, _ := p.GetService(imy)
  10. fmt.Printf("obj1 = %p,obj2 = %p\r\n", (*obj1).(*Dog), (*obj2).(*Dog))
  11. if fmt.Sprintf("%p",(*obj1).(*Dog)) != fmt.Sprintf("%p",(*obj2).(*Dog)){
  12. t.Error("两个对象不是同一个")
  13. }

获取接口和结构体的 reflect.Type:

  1. // 写法 1
  2. // 接口的 reflect.Type
  3. var animal IAnimal
  4. imy := reflect.TypeOf(&animal).Elem()
  5. my := reflect.TypeOf(Dog{})
  6. // 写法 2
  7. // 获取 reflect.Type
  8. imy := reflect.TypeOf((*IAnimal)(nil)).Elem()
  9. my := reflect.TypeOf((*Dog)(nil)).Elem()

以上两种写法都可以使用,目的在于获取到接口和结构体的 reflect.Type。不过第一种方式会实例化结构体,消耗了一次内存,并且要获取接口的 reflect.Type,是不能直接有用 reflect.TypeOf(animal) 的,需要使用 reflect.TypeOf(&animal).Elem()

然后注入服务,其生命周期为 Scoped:

  1. // 注入服务,生命周期为 scoped
  2. sc.AddServiceOf(goioc.Scope, imy, my)

当你需要 IAnimal 接口时,会自动注入 Dog 结构体给 IAnimal。

构建依赖注入服务提供器:

  1. // 构建服务 Provider
  2. serviceProvider := sc.Build()

构建完成后,即可通过 Provider 对象获取需要的实例:

  1. // 获取对象
  2. // *interface{}
  3. obj, err := serviceProvider.GetService(imy)
  4. if err != nil {
  5. panic(err)
  6. }
  7. // 转换为接口
  8. a := (*obj).(IAnimal)
  9. // a := (*obj).(*Dog)

因为使用了依赖注入,我们使用时,只需要使用接口即可,不需要知道具体的实现。

完整的代码示例:

  1. // 获取 reflect.Type
  2. imy := reflect.TypeOf((*IAnimal)(nil)).Elem()
  3. my := reflect.TypeOf((*Dog)(nil)).Elem()
  4. // 创建容器
  5. sc := &ServiceCollection{}
  6. // 注入服务,生命周期为 scoped
  7. sc.AddServiceOf(goioc.Scope, imy, my)
  8. // 构建服务 Provider
  9. serviceProvider := sc.Build()
  10. // 获取对象
  11. // *interface{} = &Dog{}
  12. obj, err := serviceProvider.GetService(imy)
  13. if err != nil {
  14. panic(err)
  15. }
  16. fmt.Println("obj 类型是", reflect.ValueOf(obj).Type())
  17. // *interface{} = &Dog{},因此需要处理指针
  18. animal := (*obj).(IAnimal)
  19. // a := (*obj).(*Dog)
  20. animal.Println("测试")

接口、结构体、结构体指针

在结构体注入时,可以对需要的字段进行自动实例化赋值,而字段可能有以下情况:

  1. // 字段是接口
  2. type Animal1 struct {
  3. Dog IAnimal `ioc:"true"`
  4. }
  5. // 字段是结构体
  6. type Animal2 struct {
  7. Dog Dog `ioc:"true"`
  8. }
  9. // 字段是结构体指针
  10. type Animal3 struct {
  11. Dog *Dog `ioc:"true"`
  12. }

首先注入前置的依赖对象:

  1. // 获取 reflect.Type
  2. imy := reflect.TypeOf((*IAnimal)(nil)).Elem()
  3. my := reflect.TypeOf((*Dog)(nil)).Elem()
  4. // 创建容器
  5. p := &ServiceCollection{}
  6. // 注入服务,生命周期为 scoped
  7. p.AddServiceOf(goioc.Scope,imy, my)
  8. p.AddService(goioc.Scope, my)

然后将我们的一些对象注入进去:

  1. t1 := reflect.TypeOf((*Animal1)(nil)).Elem()
  2. t2 := reflect.TypeOf((*Animal2)(nil)).Elem()
  3. t3 := reflect.TypeOf((*Animal3)(nil)).Elem()
  4. p.Ad(t1)
  5. p.AddServiceOf(goioc.Scope,t2)
  6. p.AddServiceOf(goioc.Scope,t3)

然后愉快地获取这些对象实例:

  1. // 构建服务 Provider
  2. p := collection.Build()
  3. v1, _ := p.GetService(t1)
  4. v2, _ := p.GetService(t2)
  5. v3, _ := p.GetService(t3)
  6. fmt.Println(*v1)
  7. fmt.Println(*v2)
  8. fmt.Println(*v3)

打印对象信息:

  1. &{0x3abdd8}
  2. &{{}}
  3. &{0x3abdd8}

可以看到,当你注入实例后,结构体字段可以是接口、结构体或结构体指针,goioc 会根据不同的情况注入对应的实例。

前面提到了对象是生命周期,这里有些地方需要注意。

如果字段是接口和结构体指针,那么 scope 生命周期时,注入的对象是同一个,可以参考前面的 v1、v3 的 Dog 字段,Dog 字段类型虽然不同,但是因为可以存储指针,因此注入的对象是同一个。如果字段是结构体,由于 Go 语言中结构体是值类型,因此给值类型赋值是,是值赋值,因此对象不是同一个了。

不会自动注入本身

下面是一个依赖注入过程:

  1. // 获取 reflect.Type
  2. imy := reflect.TypeOf((*IAnimal)(nil)).Elem()
  3. my := reflect.TypeOf((*Dog)(nil)).Elem()
  4. // 创建容器
  5. sc := &ServiceCollection{}
  6. // 注入服务,生命周期为 scoped
  7. sc.AddServiceOf(goioc.Scope,imy, my)

此时,注册的服务是 IAnimal,你只能通过 IAnimal 获取实例,无法通过 Dog 获取实例。

如果你想获取 Dog,需要自行注入:

  1. // 注入服务,生命周期为 scoped
  2. p.AddServiceOf(goioc.Scope,imy, my)
  3. p.AddService(my)

如果是结构体字段,则使用 IAnimal、Dog、*Dog 的形式都可以。

原文链接:https://www.cnblogs.com/whuanle/p/16930341.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号