This commit is contained in:
crusader 2018-04-19 14:54:36 +09:00
parent 84645a5b4d
commit 87cf94a2eb

View File

@ -108,7 +108,7 @@ func (cr *defaultComponentRegistry) RegisterResource(name string, resource inter
func GetInstance(t reflect.Type) (interface{}, error) {
return registry.GetInstance(t)
}
func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, error) {
func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (instance interface{}, err error) {
if nil == t {
return nil, fmt.Errorf("DI: t[reflect.Type] is nil")
}
@ -125,7 +125,6 @@ func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, er
td *TypeDefinition
comV interface{}
ok bool
err error
)
rt, _, _ := cur.GetTypeInfo(t)
@ -142,6 +141,16 @@ func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, er
v := reflect.New(rt)
rv := v.Elem()
instance = v.Interface()
cr.instanceByType[td.RealType] = instance
err = nil
defer func() {
if nil != err {
instance = nil
delete(cr.instanceByType, td.RealType)
}
}()
var (
annotation cda.Annotation
fV interface{}
@ -151,15 +160,17 @@ func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, er
f := rv.FieldByName(fd.FieldName)
if !f.IsValid() {
return nil, fmt.Errorf("DI: Field[%s] is not valid", fd.FieldName)
err = fmt.Errorf("DI: Field[%s] is not valid", fd.FieldName)
return
}
if !f.CanSet() {
return nil, fmt.Errorf("DI: Field[%s] can not set", fd.FieldName)
err = fmt.Errorf("DI: Field[%s] can not set", fd.FieldName)
return
}
if annotation = fd.GetAnnotationByType(cdia.InjectAnnotationType, false); nil != annotation {
if fV, err = cr.GetInstance(fd.Type); nil != err {
return nil, err
return
}
}
@ -169,19 +180,17 @@ func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, er
n = fd.FieldName
}
if fV, err = cr.GetInstanceByName(n); nil != err {
return nil, err
return
}
}
if nil != err {
return nil, fmt.Errorf("DI: %v", err)
return
}
f.Set(reflect.ValueOf(fV))
}
cr.instanceByType[td.RealType] = v.Interface()
return v.Interface(), nil
return
}
func GetInstanceByName(name string) (interface{}, error) {