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

Not providing any value group does not return an error during invocation #389

Open paullen opened 1 year ago

paullen commented 1 year ago

Describe the bug While requesting a value group in the input, in the Invoke method, dig does not check for the existence of any providers of the value group.

To Reproduce

Run the following code. The function is invoked without letting me know that there are no value group providers.

package main

import (
    "fmt"
    "log"

    "go.uber.org/dig"
)

type Logger struct{}
type LogType string

const (
    LogType_ERROR   LogType = "ERROR"
    LogType_INFO    LogType = "INFO"
    LogType_WARNING LogType = "WARNING"
)

func (l Logger) Log(logType LogType, message string) {
    log.Println(logType, message)
}

type HttpClient struct {
    logger *Logger
}

func (client *HttpClient) Get(url string) (string, error) {
    client.logger.Log(LogType_INFO, "getting "+url)

    return "You got " + url, nil
}

type HttpClientInput struct {
    dig.In
    Loggers []*Logger `group:"loggers"`
}

func NewHttpClient(input HttpClientInput) *HttpClient {
    if len(input.Loggers) > 0 {
        return &HttpClient{logger: input.Loggers[0]}
    } else {
        panic("should not execute")
    }
}

func BuildContainer() *dig.Container {
    container := dig.New()

    if err := container.Provide(NewHttpClient); err != nil {
        log.Println(err)
    }

    return container
}

func ExecuteFunction(client *HttpClient) {
    res, _ := client.Get("foo.bar")

    fmt.Println(res)
}

func main() {
    container := BuildContainer()

    if err := container.Invoke(ExecuteFunction); err != nil {
        log.Println(err)
    }

}

Expected behavior The expected behaviour would be to return an error in the Invoke function after checking for providers.

Additional context If this is by design, could you suggest ways to implement this kind of a check using current methods.

JacobOaks commented 5 months ago

Hey @paullen - as I mentioned in #184, this shouldn't be changed blindly as it would break a lot of users, but I think it's a good idea to add an option that can be passed to Dig to check for this.