-
Is there anyway to make a provider function as singleton ? There are cases we have one dependency object which must be initialized only once but is used by many other objects. How to handle those cases in uber/dig ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hello @ehsannm. For example, if you have,
And you use that with two constructors Sample code with Dig (run it at https://play.golang.org/p/bHol91PaDj3): package main
import (
"fmt"
"go.uber.org/dig"
)
type Foo struct{}
func NewFoo() *Foo {
fmt.Println("building Foo")
return new(Foo)
}
type Bar struct{}
func NewBar(*Foo) *Bar {
fmt.Println("using Foo in Bar")
return new(Bar)
}
type Baz struct{}
func NewBaz(*Foo) *Baz {
fmt.Println("using Foo in Baz")
return new(Baz)
}
func main() {
c := dig.New()
if err := c.Provide(NewFoo); err != nil {
panic(err)
}
if err := c.Provide(NewBar); err != nil {
panic(err)
}
if err := c.Provide(NewBaz); err != nil {
panic(err)
}
if err := c.Invoke(run); err != nil {
panic(err)
}
}
func run(bar *Bar, baz *Baz) {
fmt.Println("running application")
} Closing because answered. |
Beta Was this translation helpful? Give feedback.
-
@abhinav hi, i have a new question, if i want to create new instance each time, could you tell me how can do that? |
Beta Was this translation helpful? Give feedback.
Hello @ehsannm.
All functions provided to Dig/Fx are treated as singletons and re-used in every other function.
For example, if you have,
And you use that with two constructors
NewBar(*Foo) *Bar
andNewBaz(*Foo) *Bar
,both Dig and Fx will instantiate
*Foo
only once (calling that print statement only once)and share it between Bar and Baz.
Sample code with Dig (run it at https://play.golang.org/p/bHol91PaDj3):