Skip to content

Instantly share code, notes, and snippets.

@dzungtran
Created November 10, 2020 11:31
Show Gist options
  • Save dzungtran/cdf114a09a3f4c1a2a891c0957f935ba to your computer and use it in GitHub Desktop.
Save dzungtran/cdf114a09a3f4c1a2a891c0957f935ba to your computer and use it in GitHub Desktop.
Example dependencies injection with dig
package main
import (
"fmt"
"go.uber.org/dig"
)
type Say struct {
Name string
}
func (s Say) Hello() {
fmt.Println("HELLO ", s.Name)
}
type Eat struct {
Meal string
}
func (e Eat) Diner() {
fmt.Println(e.Meal, "!!!")
}
type Hoooman struct {
dig.In
Say *Say
Eat *Eat
}
func main() {
c := dig.New()
// Provide a Config object. This can fail to decode.
err := c.Provide(func() (*Say, error) {
return &Say{Name: "Dzung"}, nil
})
if err != nil {
panic(err)
}
// Provide a way to build the logger based on the configuration.
err = c.Provide(func() (*Eat, error) {
return &Eat{Meal: "Pizza"}, nil
})
if err != nil {
panic(err)
}
// Invoke a function that requires the injected object
err = c.Invoke(func(e *Eat, s *Say) {
s.Hello()
e.Diner()
})
if err != nil {
panic(err)
}
var hoo *Hoooman
// Invoke with Parameter Objects
err = c.Invoke(func(h Hoooman) {
hoo = &h
})
if err != nil {
panic(err)
}
hoo.Say.Hello()
hoo.Eat.Diner()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment