4 Star 10 Fork 2

Gitee 极速下载/go-ioc

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://github.com/mylxsw/go-ioc
克隆/下载
entity.go 1.61 KB
一键复制 编辑 原始数据 按行查看 历史
package ioc
import (
"fmt"
"reflect"
"sync"
)
// Entity represent an entity in container
type Entity struct {
lock sync.RWMutex
key any // entity key
initializeFunc any // initializeFunc is a func to initialize entity
value any // the value of initializeFunc
typ reflect.Type // the type of value
overridable bool // identify whether the entity can be overridden
prototype bool
c *container
}
// Value instance value if not initialized
func (e *Entity) Value(provider EntitiesProvider) (interface{}, error) {
if e.prototype {
return e.createValue(provider)
}
e.lock.Lock()
defer e.lock.Unlock()
if e.value == nil {
val, err := e.createValue(provider)
if err != nil {
return nil, err
}
e.value = val
}
return e.value, nil
}
func (e *Entity) createValue(provider EntitiesProvider) (interface{}, error) {
initializeValue := reflect.ValueOf(e.initializeFunc)
argValues, err := e.c.funcArgs(initializeValue.Type(), provider)
if err != nil {
return nil, err
}
returnValues := reflect.ValueOf(e.initializeFunc).Call(argValues)
if len(returnValues) <= 0 {
return nil, buildInvalidReturnValueCountError("expect greater than 0, got 0")
}
if len(returnValues) > 1 && !returnValues[1].IsNil() && returnValues[1].Interface() != nil {
if err, ok := returnValues[1].Interface().(error); ok {
return nil, fmt.Errorf("(%s) %w", e.key, err)
}
// 如果第二个返回值不是 error,则强制转换为 error
return nil, fmt.Errorf("(%s) %v", e.key, returnValues[1].Interface())
}
return returnValues[0].Interface(), nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mirrors/go-ioc.git
git@gitee.com:mirrors/go-ioc.git
mirrors
go-ioc
go-ioc
master

搜索帮助