Skip to content

Singleton Provider #291

Description

@ehsannm

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 ?

Activity

  1. abhinav commented on Nov 4, 2021

    @abhinav
    Collaborator

    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")
    	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.
    If I misunderstood the question, feel free to open a new issue with more details.
    Thanks!

  2. dalianzhu commented on Aug 16, 2022

    @dalianzhu

    @abhinav hi, i have a new question, if i want to create new instance each time, could you tell me how can do that?

  3. locked and limited conversation to collaborators on Aug 16, 2022
  4. converted this issue into a discussion #353 on Aug 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions