Skip to content

Singleton Provider #353

Answered by abhinav
ehsannm asked this question in Q&A
Sep 2, 2021 · 2 comments · 1 reply
Discussion options

You must be logged in to vote

Hello @ehsannm.
All functions provided to Dig/Fx are treated as singletons and re-used in every other function.

For example, if you have,

func NewFoo() *Foo {
	fmt.Println("building Foo")
	return // ...
}

And you use that with two constructors NewBar(*Foo) *Bar and NewBaz(*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):

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")…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by abhinav
Comment options

You must be logged in to vote
1 reply
@abhinav
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #291 on August 16, 2022 16:24.