2017-12-03 10:55:10 +00:00
|
|
|
package registry
|
|
|
|
|
2017-12-03 13:54:09 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
cda "git.loafle.net/commons_go/di/annotation"
|
2017-12-03 13:54:09 +00:00
|
|
|
cdur "git.loafle.net/commons_go/di/util/reflect"
|
|
|
|
)
|
2017-12-03 10:55:10 +00:00
|
|
|
|
|
|
|
type ComponentRegistry interface {
|
2017-12-05 10:02:41 +00:00
|
|
|
RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) error
|
|
|
|
RegisterFactory(i interface{}, ca *cda.ComponentAnnotation) error
|
2017-12-03 10:55:10 +00:00
|
|
|
|
|
|
|
GetInstance(t reflect.Type) (interface{}, error)
|
|
|
|
GetInstanceByName(name string) (interface{}, error)
|
|
|
|
}
|
2017-12-03 13:54:09 +00:00
|
|
|
|
|
|
|
type defaultComponentRegistry struct {
|
2017-12-05 10:02:41 +00:00
|
|
|
definitionsByType map[reflect.Type]*ComponentDefinition
|
|
|
|
|
|
|
|
definitionByName map[string]*ComponentDefinition
|
2017-12-03 13:54:09 +00:00
|
|
|
}
|
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
func (cr *defaultComponentRegistry) RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) error {
|
2017-12-03 13:54:09 +00:00
|
|
|
if nil == t {
|
|
|
|
return fmt.Errorf("DI: t[reflect.Type] is nil")
|
|
|
|
}
|
|
|
|
if !cdur.IsTypeKind(t, reflect.Struct, true) {
|
|
|
|
return fmt.Errorf("DI: t[reflect.Type] must be specified but is %v", t)
|
|
|
|
}
|
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
rt, pkgName, tName := cdur.GetTypeName(t)
|
2017-12-03 13:54:09 +00:00
|
|
|
cr.definitions[name] = rt
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, error) {
|
|
|
|
if nil == t {
|
|
|
|
return nil, fmt.Errorf("DI: t[reflect.Type] is nil")
|
|
|
|
}
|
2017-12-03 13:54:09 +00:00
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
cd, ok := cr.definitionsByType[t]
|
|
|
|
if !ok {
|
|
|
|
cd = cr.buildDefinition(t)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
2017-12-03 13:54:09 +00:00
|
|
|
}
|
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
func (cr *defaultComponentRegistry) GetInstanceByName(name string) (interface{}, error) {
|
2017-12-03 13:54:09 +00:00
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2017-12-05 10:02:41 +00:00
|
|
|
func (cr *defaultComponentRegistry) buildDefinition(t reflect.Type) (*ComponentDefinition, error) {
|
|
|
|
if nil == t {
|
|
|
|
return nil, fmt.Errorf("DI: t[reflect.Type] is nil")
|
|
|
|
}
|
|
|
|
|
|
|
|
rt, pkgName, tName := cdur.GetTypeName(t)
|
|
|
|
cd := &ComponentDefinition{}
|
|
|
|
cd.PkgName = pkgName
|
|
|
|
cd.TypeName = tName
|
|
|
|
cd.Type = t
|
|
|
|
cd.RealType = rt
|
2017-12-03 13:54:09 +00:00
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|