diff --git a/registry/registry.go b/registry/registry.go index e88b93d..92b023c 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -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) {