uber-go / dig

A reflection based dependency injection toolkit for Go.
https://go.uber.org/dig
MIT License
3.88k stars 206 forks source link

Build value group values using their original scope #393

Closed JacobOaks closed 1 year ago

JacobOaks commented 1 year ago

We call simple providers with their original scope. (ref) This allows decorators to be applied even if the constructor is exported via dig.Export(true).

However, we call value group value providers with whatever scope we found them in: (ref)

This has the consequence of causing exported value group value providers within a module to not be able to be decorated by decorators within the same module, when using dig.Export(true), unlike their simple provider counterpart.

For example (playground):

type Foo struct{}
type FooResults struct {
    dig.Out

    Foo Foo `group:"foos"`
}

func NewFoo(s string) FooResults {
    fmt.Printf("String in NewFoo: %q\n", s)
    return FooResults{
        Foo: Foo{},
    }
}

type Bar struct{}

func NewBar(s string) Bar {
    fmt.Printf("String in NewBar: %q\n", s)
    return Bar{}
}

type UseFooAndBarParams struct {
    dig.In

    Foos []Foo `group:"foos"`
    Bar  Bar
}

func UseFooAndBar(UseFooAndBarParams) {}

func main() {
    c := dig.New()
    c.Provide(func() string { return "base" })
    child := c.Scope("child")
    child.Decorate(func(s string) string {
        return s + "-decorated"
    })
    child.Provide(NewFoo, dig.Export(true))
    child.Provide(NewBar, dig.Export(true))
}

// Output:
// String in NewFoo: "base"
// String in NewBar: "base-decorated"

Since we use dig.Export(true) by default in Fx, this is the default behavior for value group providers, see https://github.com/uber-go/fx/issues/1104

This commit changes callGroupProviders to use the value group provider's original scope as well, and adds a test to verify the behavior is fixed.

codecov[bot] commented 1 year ago

Codecov Report

Merging #393 (cc4ce88) into master (a30081d) will not change coverage. The diff coverage is 100.00%.

@@           Coverage Diff           @@
##           master     #393   +/-   ##
=======================================
  Coverage   98.39%   98.39%           
=======================================
  Files          22       22           
  Lines        1492     1492           
=======================================
  Hits         1468     1468           
  Misses         15       15           
  Partials        9        9           
Files Changed Coverage Δ
param.go 97.34% <100.00%> (ø)

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more