This commit is contained in:
crusader 2017-12-06 15:30:49 +09:00
parent 700f188618
commit 878c1feada

View File

@ -20,6 +20,7 @@ var registry ComponentRegistry
type ComponentRegistry interface { type ComponentRegistry interface {
RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) RegisterType(t reflect.Type, ca *cda.ComponentAnnotation)
RegisterResource(name string, resource interface{}) error
GetInstance(t reflect.Type) (interface{}, error) GetInstance(t reflect.Type) (interface{}, error)
GetInstanceByName(name string) (interface{}, error) GetInstanceByName(name string) (interface{}, error)
@ -29,6 +30,7 @@ func newRegistry() ComponentRegistry {
r := &defaultComponentRegistry{} r := &defaultComponentRegistry{}
r.definitionByType = make(map[reflect.Type]*TypeDefinition, 0) r.definitionByType = make(map[reflect.Type]*TypeDefinition, 0)
r.definitionByName = make(map[string]*TypeDefinition, 0) r.definitionByName = make(map[string]*TypeDefinition, 0)
r.resourceByName = make(map[string]interface{}, 0)
return r return r
} }
@ -36,6 +38,7 @@ func newRegistry() ComponentRegistry {
type defaultComponentRegistry struct { type defaultComponentRegistry struct {
definitionByType map[reflect.Type]*TypeDefinition definitionByType map[reflect.Type]*TypeDefinition
definitionByName map[string]*TypeDefinition definitionByName map[string]*TypeDefinition
resourceByName map[string]interface{}
} }
func RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) { func RegisterType(t reflect.Type, ca *cda.ComponentAnnotation) {
@ -78,6 +81,18 @@ func (cr *defaultComponentRegistry) RegisterType(t reflect.Type, ca *cda.Compone
cr.definitionByName[name] = td cr.definitionByName[name] = td
} }
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
}
func GetInstance(t reflect.Type) (interface{}, error) { func GetInstance(t reflect.Type) (interface{}, error) {
return registry.GetInstance(t) return registry.GetInstance(t)
} }