dig icon indicating copy to clipboard operation
dig copied to clipboard

Declaring Provider/Injector using Comment?

Open zsh1995 opened this issue 4 years ago • 1 comments

Hi, I'm considering using comment to declare provider/injector while it's boring to pass provider/injector to dig container:

c := dig.New()
err = c.Provide(NewFoo)
if err != nil {
    return errors.WithMessage(err, "provide NewFoo failed")
}

Using comment,we could write code like this:

//go:generate diggen

// dig:provider
func NewFoo() Foo {
    return Foo{}
}

// dig:invoke
func InitFoo(foo Foo) {
    // do something with foo
}

Then some tools can generate code from comment.

func Inject(c *dig.Container) error {
    ver err error
    err = c.Provide(NewFoo)
    if err != nil {
        return errors.WithMessage(err, "provide NewFoo failed")
    }
    return nil
}

func Invoke(c *dig.Container) error {
    var err error
    err = c.Invoke(InitFoo)
        if err != nil {
        return errors.WithMessage(err, "invoke InitFoo failed")
    }
    return nil
}

Is this a good way?

zsh1995 avatar Sep 03 '21 08:09 zsh1995

Hey there! Although we don't have plans to support such functionality for Fx or Dig, we can see how this might be convenient.

One limitation I foresee is that this will work only for top-level functions--no methods. That may be an acceptable trade-off for this use case.

If you do implement something like this, feel free to share it with us. We will be happy to add a Community section to our README and include a link to it.

abhinav avatar Nov 04 '21 22:11 abhinav