defval / di

🛠 A full-featured dependency injection container for go programming language.
MIT License
232 stars 13 forks source link

Overriding a value from a parent di container #50

Open matdurand opened 11 months ago

matdurand commented 11 months ago

Is it possible to override a value that is already defined in a parent container?

For example, let's say I want to override the Logger for a specific DI container like this

type Logger interface {
}

type Logger1 struct{}
type Logger2 struct{}

func main() {
    root, err := di.New(
        di.ProvideValue(Logger1{}, di.As(new(Logger))),
    )
    if err != nil {
        panic(err)
    }

    child, err := di.New(
        di.ProvideValue(Logger2{}, di.As(new(Logger))),
    )
    if err != nil {
        panic(err)
    }

    err = child.AddParent(root)
    if err != nil {
        panic(err)
    }

    var lg Logger
    err = child.Resolve(&lg)
    if err != nil {
        panic(err)
    }
}

I get

 multiple definitions of main.Logger, maybe you need to use group type: []main.Logger