...
1# inject
2--
3 import "github.com/codegangsta/inject"
4
5inject包提供了多种对实体的映射和依赖注入方式。
6
7## 用法
8
9#### func InterfaceOf
10
11```go
12func InterfaceOf(value interface{}) reflect.Type
13```
14函数InterfaceOf返回指向接口类型的指针。如果传入的value值不是指向接口的指针,将抛出一个panic异常。
15
16#### type Applicator
17
18```go
19type Applicator interface {
20 // 在Type map中维持对结构体中每个域的引用并用'inject'来标记
21 // 如果注入失败将会返回一个error.
22 Apply(interface{}) error
23}
24```
25
26Applicator接口表示到结构体的依赖映射关系。
27
28#### type Injector
29
30```go
31type Injector interface {
32 Applicator
33 Invoker
34 TypeMapper
35 // SetParent用来设置父injector. 如果在当前injector的Type map中找不到依赖,
36 // 将会继续从它的父injector中找,直到返回error.
37 SetParent(Injector)
38}
39```
40
41Injector接口表示对结构体、函数参数的映射和依赖注入。
42
43#### func New
44
45```go
46func New() Injector
47```
48New创建并返回一个Injector.
49
50#### type Invoker
51
52```go
53type Invoker interface {
54 // Invoke尝试将interface{}作为一个函数来调用,并基于Type为函数提供参数。
55 // 它将返回reflect.Value的切片,其中存放原函数的返回值。
56 // 如果注入失败则返回error.
57 Invoke(interface{}) ([]reflect.Value, error)
58}
59```
60
61Invoker接口表示通过反射进行函数调用。
62
63#### type TypeMapper
64
65```go
66type TypeMapper interface {
67 // 基于调用reflect.TypeOf得到的类型映射interface{}的值。
68 Map(interface{}) TypeMapper
69 // 基于提供的接口的指针映射interface{}的值。
70 // 该函数仅用来将一个值映射为接口,因为接口无法不通过指针而直接引用到。
71 MapTo(interface{}, interface{}) TypeMapper
72 // 为直接插入基于类型和值的map提供一种可能性。
73 // 它使得这一类直接映射成为可能:无法通过反射直接实例化的类型参数,如单向管道。
74 Set(reflect.Type, reflect.Value) TypeMapper
75 // 返回映射到当前类型的Value. 如果Type没被映射,将返回对应的零值。
76 Get(reflect.Type) reflect.Value
77}
78```
79
80TypeMapper接口用来表示基于类型到接口值的映射。
81
82
83## 译者
84
85张强 (qqbunny@yeah.net)
View as plain text