di/registry/registry.go
crusader e1da1222c6 ing
2018-03-21 21:31:37 +09:00

316 lines
7.3 KiB
Go

package registry
import (
"fmt"
"log"
"reflect"
"runtime"
"strings"
cda "git.loafle.net/commons_go/di/annotation"
cdia "git.loafle.net/commons_go/di/injection/annotation"
cur "git.loafle.net/commons_go/util/reflect"
)
func init() {
registry = newRegistry()
}
var registry ComponentRegistry
type ComponentRegistry interface {
RegisterType(t reflect.Type) error
RegisterResource(name string, resource interface{}) error
GetInstance(t reflect.Type) (interface{}, error)
GetInstances(ts []reflect.Type) ([]interface{}, error)
GetInstanceByName(name string) (interface{}, error)
GetInstancesByAnnotationName(n string) ([]interface{}, error)
}
func newRegistry() ComponentRegistry {
r := &defaultComponentRegistry{}
r.definitionByType = make(map[reflect.Type]*TypeDefinition, 0)
r.definitionByName = make(map[string]*TypeDefinition, 0)
r.instanceByType = make(map[reflect.Type]interface{}, 0)
r.resourceByName = make(map[string]interface{}, 0)
return r
}
type defaultComponentRegistry struct {
definitionByType map[reflect.Type]*TypeDefinition
definitionByName map[string]*TypeDefinition
instanceByType map[reflect.Type]interface{}
resourceByName map[string]interface{}
}
func RegisterType(t reflect.Type) error {
pc, _, _, ok := runtime.Caller(1)
details := runtime.FuncForPC(pc)
if ok && details != nil {
log.Printf("called from %s", details.Name())
}
return registry.RegisterType(t)
}
func (cr *defaultComponentRegistry) RegisterType(t reflect.Type) error {
if nil == t {
return fmt.Errorf("DI: t[reflect.Type] is nil")
}
if !cur.IsTypeKind(t, reflect.Struct, true) {
return fmt.Errorf("DI: t[reflect.Type] must be specified but is %v", t)
}
td, err := cr.buildDefinition(t)
if nil != err {
return fmt.Errorf("DI: %v", err)
}
if _, ok := cr.definitionByType[td.RealType]; ok {
return fmt.Errorf("DI: The type[%s] of Component is exist already", td.FullName)
}
cr.definitionByType[td.RealType] = td
name := td.TypeName
if a := td.GetAnnotationByType(reflect.TypeOf((*cdia.Component)(nil)), true); nil != a {
ca := a.(*cdia.Component)
if "" != strings.Trim(ca.Name, " ") {
name = ca.Name
}
}
if eTD, ok := cr.definitionByName[name]; ok {
return fmt.Errorf("DI: The name[%s] of Component is exist already type[%s]", name, eTD.FullName)
}
cr.definitionByName[name] = td
return nil
}
func RegisterResource(name string, resource interface{}) error {
return registry.RegisterResource(name, resource)
}
func (cr *defaultComponentRegistry) RegisterResource(name string, resource interface{}) error {
if _, ok := cr.resourceByName[name]; ok {
return fmt.Errorf("DI: Resource[%s] is already exist", name)
}
cr.resourceByName[name] = resource
return nil
}
// GetInstance returns instance of type
// t must be pointer of struct
func GetInstance(t reflect.Type) (interface{}, error) {
return registry.GetInstance(t)
}
func (cr *defaultComponentRegistry) GetInstance(t reflect.Type) (interface{}, error) {
if nil == t {
return nil, fmt.Errorf("DI: t[reflect.Type] is nil")
}
if reflect.Ptr != t.Kind() {
return nil, fmt.Errorf("DI: t[reflect.Type] must be pointer of struct")
}
if reflect.Struct != t.Elem().Kind() {
return nil, fmt.Errorf("DI: t[reflect.Type] must be pointer of struct")
}
var err error
rt, _, _ := cur.GetTypeInfo(t)
td, ok := cr.definitionByType[rt]
if !ok {
td, err = cr.buildDefinition(t)
if nil != err {
return nil, fmt.Errorf("DI: %v", err)
}
}
comV, ok := cr.instanceByType[td.RealType]
if ok {
return comV, nil
}
v := reflect.New(rt)
rv := v.Elem()
var annotation cda.Annotation
var fV interface{}
for _, fd := range td.Fields {
f := rv.FieldByName(fd.FieldName)
if !f.IsValid() {
return nil, fmt.Errorf("DI: Field[%s] is not valid", fd.FieldName)
}
if !f.CanSet() {
return nil, fmt.Errorf("DI: Field[%s] can not set", fd.FieldName)
}
if annotation = fd.GetAnnotationByType(reflect.TypeOf((*cdia.Inject)(nil)), false); nil != annotation {
fV, err = cr.GetInstance(fd.Type)
if nil != err {
return nil, err
}
}
if annotation = fd.GetAnnotationByType(reflect.TypeOf((*cdia.Resource)(nil)), false); nil != annotation {
n := annotation.(*cdia.Resource).Name
if "" == n {
n = fd.FieldName
}
fV, err = cr.GetInstanceByName(n)
if nil != err {
return nil, err
}
}
if nil != err {
return nil, fmt.Errorf("DI: %v", err)
}
f.Set(reflect.ValueOf(fV))
}
cr.instanceByType[td.RealType] = v.Interface()
return v.Interface(), nil
}
func GetInstanceByName(name string) (interface{}, error) {
return registry.GetInstanceByName(name)
}
func (cr *defaultComponentRegistry) GetInstanceByName(name string) (interface{}, error) {
v, ok := cr.resourceByName[name]
if ok {
return v, nil
}
return nil, fmt.Errorf("DI: Resource[%s] is not exist", name)
}
// GetInstances returns instance of annotated
// n must be name of registered annotation
func GetInstances(ts []reflect.Type) ([]interface{}, error) {
return registry.GetInstances(ts)
}
func (cr *defaultComponentRegistry) GetInstances(ts []reflect.Type) ([]interface{}, error) {
var (
i interface{}
err error
)
instances := make([]interface{}, 0)
for _, t := range ts {
i, err = cr.GetInstance(t)
if nil != err {
return nil, err
}
instances = append(instances, i)
}
return instances, nil
}
// GetInstancesByAnnotationName returns instance of annotated
// n must be name of registered annotation
func GetInstancesByAnnotationName(n string) ([]interface{}, error) {
return registry.GetInstancesByAnnotationName(n)
}
func (cr *defaultComponentRegistry) GetInstancesByAnnotationName(n string) ([]interface{}, error) {
var (
i interface{}
err error
)
instances := make([]interface{}, 0)
for _, td := range cr.definitionByType {
if nil != td.GetAnnotation(n) {
i, err = cr.GetInstance(td.Type)
if nil != err {
return nil, err
}
instances = append(instances, i)
}
}
return instances, nil
}
func (cr *defaultComponentRegistry) buildDefinition(t reflect.Type) (*TypeDefinition, error) {
if nil == t {
return nil, fmt.Errorf("t[reflect.Type] is nil")
}
rt, pkgName, tName := cur.GetTypeInfo(t)
td := &TypeDefinition{}
td.FullName = FullName(pkgName, tName)
td.PkgName = pkgName
td.TypeName = tName
td.Type = t
td.RealType = rt
td.Fields = make([]*FieldDefinition, 0)
parseFields(rt, td)
return td, nil
}
func parseFields(t reflect.Type, td *TypeDefinition) {
// fields := make([]*FieldDefinition, 0)
rt, _, _ := cur.GetTypeInfo(t)
if reflect.Struct != rt.Kind() {
return
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.Anonymous {
if parseAnonymousField(f, td) {
continue
}
parseFields(f.Type, td)
} else {
as, err := cda.ParseAnnotation(f.Tag)
if nil != err {
return
}
if nil != as && 0 < len(as) {
fRT, fPkgName, fTName := cur.GetTypeInfo(f.Type)
fd := &FieldDefinition{
FieldName: f.Name,
PkgName: fPkgName,
TypeName: fTName,
Type: f.Type,
RealType: fRT,
Annotations: as,
}
td.Fields = append(td.Fields, fd)
}
}
}
}
func parseAnonymousField(f reflect.StructField, td *TypeDefinition) bool {
ct := reflect.TypeOf((*cda.TypeAnnotation)(nil)).Elem()
if f.Type != ct {
return false
}
as, err := cda.ParseAnnotation(f.Tag)
if nil != err {
return false
}
if nil != as && 0 < len(as) {
td.TypeAnnotations = as
return true
}
return false
}