71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package registry
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
|
|
cda "git.loafle.net/commons_go/di/annotation"
|
|
cdur "git.loafle.net/commons_go/di/util/reflect"
|
|
)
|
|
|
|
type ComponentRegistry interface {
|
|
RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) error
|
|
RegisterFactory(i interface{}, ca *cda.ComponentAnnotation) error
|
|
|
|
GetInstance(t reflect.Type) (interface{}, error)
|
|
GetInstanceByName(name string) (interface{}, error)
|
|
}
|
|
|
|
type defaultComponentRegistry struct {
|
|
definitionsByType map[reflect.Type]*ComponentDefinition
|
|
|
|
definitionByName map[string]*ComponentDefinition
|
|
}
|
|
|
|
func (cr *defaultComponentRegistry) RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) error {
|
|
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)
|
|
}
|
|
|
|
rt, pkgName, tName := cdur.GetTypeName(t)
|
|
cr.definitions[name] = rt
|
|
|
|
return nil
|
|
}
|
|
|
|
func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, error) {
|
|
if nil == t {
|
|
return nil, fmt.Errorf("DI: t[reflect.Type] is nil")
|
|
}
|
|
|
|
cd, ok := cr.definitionsByType[t]
|
|
if !ok {
|
|
cd = cr.buildDefinition(t)
|
|
}
|
|
|
|
return nil, nil
|
|
}
|
|
|
|
func (cr *defaultComponentRegistry) GetInstanceByName(name string) (interface{}, error) {
|
|
|
|
return nil, nil
|
|
}
|
|
|
|
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
|
|
|
|
return nil, nil
|
|
}
|