Skip to content

Commit 37d7f84

Browse files
committed
Merge pull request #18 from codegangsta/JMS-Implementors
inject will now inject interface implementors as dependencies
2 parents 8822b07 + c5f917d commit 37d7f84

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

inject.go

+19
Original file line numberDiff line numberDiff line change
@@ -157,10 +157,29 @@ func (i *injector) Set(typ reflect.Type, val reflect.Value) TypeMapper {
157157

158158
func (i *injector) Get(t reflect.Type) reflect.Value {
159159
val := i.values[t]
160+
161+
if val.IsValid() {
162+
return val
163+
}
164+
165+
// no concrete types found, try to find implementors
166+
// if t is an interface
167+
if t.Kind() == reflect.Interface {
168+
for k, v := range i.values {
169+
if k.Implements(t) {
170+
val = v
171+
break
172+
}
173+
}
174+
}
175+
176+
// Still no type found, try to look it up on the parent
160177
if !val.IsValid() && i.parent != nil {
161178
val = i.parent.Get(t)
162179
}
180+
163181
return val
182+
164183
}
165184

166185
func (i *injector) SetParent(parent Injector) {

inject_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package inject_test
22

33
import (
4+
"fmt"
45
"github.com/codegangsta/inject"
56
"reflect"
67
"testing"
@@ -15,6 +16,14 @@ type TestStruct struct {
1516
Dep3 string
1617
}
1718

19+
type Greeter struct {
20+
Name string
21+
}
22+
23+
func (g *Greeter) String() string {
24+
return "Hello, My name is" + g.Name
25+
}
26+
1827
/* Test Helpers */
1928
func expect(t *testing.T, a interface{}, b interface{}) {
2029
if a != b {
@@ -140,3 +149,11 @@ func Test_InjectorSetParent(t *testing.T) {
140149

141150
expect(t, injector2.Get(inject.InterfaceOf((*SpecialString)(nil))).IsValid(), true)
142151
}
152+
153+
func TestInjectImplementors(t *testing.T) {
154+
injector := inject.New()
155+
g := &Greeter{"Jeremy"}
156+
injector.Map(g)
157+
158+
expect(t, injector.Get(inject.InterfaceOf((*fmt.Stringer)(nil))).IsValid(), true)
159+
}

0 commit comments

Comments
 (0)