-
Notifications
You must be signed in to change notification settings - Fork 0
/
container.go
65 lines (57 loc) · 1.54 KB
/
container.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
package dependencyinjection
import (
"github.com/yoyofxteam/dependencyinjection/di"
)
// New creates a new container with provided options.
func New(options ...Option) *Container {
var c = &Container{
container: di.New(),
}
// apply options.
for _, opt := range options {
opt.apply(c)
}
c.compile()
return c
}
// Container is a dependency injection container.
type Container struct {
providers []provide
container *di.Container
}
// Extract populates given target pointer with type instance provided in the container.
//
// var server *http.Server
// if err = container.Extract(&server); err != nil {
// // extract failed
// }
//
// If the target type does not exist in a container or instance type building failed, Extract() returns an error.
// Use ExtractOption for modifying the behavior of this function.
func (c *Container) Extract(target interface{}, options ...ExtractOption) (err error) {
var params = di.ExtractParams{}
// apply extract options
for _, opt := range options {
opt.apply(¶ms)
}
return c.container.Extract(target, params)
}
// Invoke invokes custom function. Dependencies of function will be resolved via container.
func (c *Container) Invoke(fn interface{}) error {
return c.container.Invoke(fn)
}
// Cleanup cleanup container.
func (c *Container) Cleanup() {
c.container.Cleanup()
}
func (c *Container) compile() {
for _, po := range c.providers {
c.container.Provide(po.provider, po.params)
}
c.container.Compile()
return
}
type provide struct {
provider interface{}
params di.ProvideParams
}