Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Declaring Provider/Injector using Comment? #292

Open
zsh1995 opened this issue Sep 3, 2021 · 1 comment
Open

Declaring Provider/Injector using Comment? #292

zsh1995 opened this issue Sep 3, 2021 · 1 comment

Comments

@zsh1995
Copy link

zsh1995 commented Sep 3, 2021

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?

@abhinav
Copy link
Collaborator

abhinav commented Nov 4, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants