-
Notifications
You must be signed in to change notification settings - Fork 1
/
factory.go
69 lines (59 loc) · 1.79 KB
/
factory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package injector
import (
"fmt"
"reflect"
)
type FactoryFunction func() (interface{}, error)
// TransientFactory is a function wrapper for a transient dependency
// to provide dependency injection inside the factory function
func TransientFactory(depFactory interface{}) (FactoryFunction, error) {
depFactoryType := reflect.TypeOf(depFactory)
depFactoryValue := reflect.ValueOf(depFactory)
if depFactoryType.Kind() != reflect.Func {
return nil, ErrorDepFactoryNotAFunc
}
if depFactoryType.NumOut() != 1 {
return nil, ErrorDepFactoryReturnCount
}
// Dependency-Inject arguments for factory function
args, err := injectFuncArgs(depFactory)
if err != nil {
return nil, err
}
// Create factory wrapper to inject dependencies
return func() (dep interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("dependency injection failed because factory paniced, recovered value: %v", r)
dep = nil
}
}()
returnVals := depFactoryValue.Call(args)
dep = returnVals[0].Interface()
return
}, nil
}
// SingletonFactory is a function wrapper for a singleton dependency factory
// to provide dependency injection inside the factory function and to retain
// the singleton instance once instantiated.
func SingletonFactory(depFactory interface{}) (FactoryFunction, error) {
factory, err := TransientFactory(depFactory)
if err != nil {
return nil, err
}
// Wrap factory wrapper to ensure existing singleton value is used if
// it already exists.
var singleton interface{}
return func() (interface{}, error) {
if singleton != nil {
return singleton, nil
}
// Singleton is not ready, call transient factory to instantiate dependency
dep, err := factory()
if err != nil {
return nil, err
}
singleton = dep
return singleton, nil
}, nil
}