Open
Description
package main
import (
"fmt"
"go.uber.org/dig"
)
type Animal interface {
Say()
}
type Dog struct {
Name string
}
// NewDog dig provider
func NewDog() *Dog {
println("new dog")
return &Dog{
Name: "xiaohei",
}
}
func (d *Dog) Say() {
fmt.Printf("%s say\n", d.Name)
}
type Cat struct {
Name string
}
func (c *Cat) Say() {
fmt.Printf("%s say\n", c.Name)
}
// NewCat dig provider
func NewCat() *Cat {
println("new cat")
return &Cat{
Name: "xiaohong",
}
}
type Zoo struct {
BlackDog *Dog
RedCat *Cat
}
type injector struct {
dig.In
BlackDog *Dog `name:"dog"`
RedCat *Cat `name:"cat"`
}
func NewZoo(inj injector) *Zoo {
println("new zoo")
return &Zoo{
BlackDog: inj.BlackDog,
RedCat: inj.RedCat,
}
}
func main() {
container := dig.New()
container.Provide(NewDog, dig.Name("dog"))
container.Provide(NewCat, dig.Name("cat"))
container.Provide(NewZoo)
container.Invoke(func(z *Zoo) {
println("----")
z.RedCat.Say()
})
}
As above, I must create injector struct as param to NewZoo. How can I simplify it.Like this
type Zoo struct {
dig.In
BlackDog *Dog `name:"dog"`
RedCat *Cat `name:"cat"`
}
//type injector struct {
// dig.In
// BlackDog *Dog `name:"dog"`
// RedCat *Cat `name:"cat"`
//}
func NewZoo(inj Zoo) *Zoo {
println("new zoo")
return &Zoo{
BlackDog: inj.BlackDog,
RedCat: inj.RedCat,
}
}