I have a struct StructDependingOnInterface which depends on MyInterface interface. I'd like the struct Implementation to be injected into bar when StructDependingOnInterface is instantiated.
I have tried doing this with facebookgo/inject library, but it seems like it doesn't work with interfaces. s.bar is always nil.
package main
import (
"fmt"
"log"
"github.com/facebookgo/inject"
)
type MyInterface interface {
Foo()
}
type Implementation struct{}
func (imp *Implementation) Foo() {
fmt.Println("Hello")
}
type StructDependingOnInterface struct {
bar MyInterface `inject:""`
}
func main() {
var g inject.Graph
err := g.Provide(
&inject.Object{Value: &Implementation{}},
)
if err != nil {
log.Fatal(err)
}
g.Populate()
s := &StructDependingOnInterface{}
s.bar.Foo()
}
Does the language go allows what I'm trying to do ?
Is there an alternative of facebookgo/inject that would fits my need ?
implementationstruct forFoo(). Also you cannot call Foo on nil Pointer as in you did fors.bar.Foo()where is s.bar is nil cannot be deference to callFoo(). As the error showsbarI believe, i.e. changing it toBar... see here: github.com/facebookgo/inject/blob/…