Skip to content

Commit

Permalink
Merge pull request #18 from codegangsta/JMS-Implementors
Browse files Browse the repository at this point in the history
inject will now inject interface implementors as dependencies
  • Loading branch information
codegangsta committed Apr 25, 2014
2 parents 8822b07 + c5f917d commit 37d7f84
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions inject.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,29 @@ func (i *injector) Set(typ reflect.Type, val reflect.Value) TypeMapper {

func (i *injector) Get(t reflect.Type) reflect.Value {
val := i.values[t]

if val.IsValid() {
return val
}

// no concrete types found, try to find implementors
// if t is an interface
if t.Kind() == reflect.Interface {
for k, v := range i.values {
if k.Implements(t) {
val = v
break
}
}
}

// Still no type found, try to look it up on the parent
if !val.IsValid() && i.parent != nil {
val = i.parent.Get(t)
}

return val

}

func (i *injector) SetParent(parent Injector) {
Expand Down
17 changes: 17 additions & 0 deletions inject_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package inject_test

import (
"fmt"
"github.com/codegangsta/inject"
"reflect"
"testing"
Expand All @@ -15,6 +16,14 @@ type TestStruct struct {
Dep3 string
}

type Greeter struct {
Name string
}

func (g *Greeter) String() string {
return "Hello, My name is" + g.Name
}

/* Test Helpers */
func expect(t *testing.T, a interface{}, b interface{}) {
if a != b {
Expand Down Expand Up @@ -140,3 +149,11 @@ func Test_InjectorSetParent(t *testing.T) {

expect(t, injector2.Get(inject.InterfaceOf((*SpecialString)(nil))).IsValid(), true)
}

func TestInjectImplementors(t *testing.T) {
injector := inject.New()
g := &Greeter{"Jeremy"}
injector.Map(g)

expect(t, injector.Get(inject.InterfaceOf((*fmt.Stringer)(nil))).IsValid(), true)
}

0 comments on commit 37d7f84

Please sign in to comment.