fx
fx copied to clipboard
OnStart/OnStop annotations: Suport non-standard signatures
Is your feature request related to a problem? Please describe.
fx.OnStart and fx.OnStop annotations currently require that hooks accept a context.Context as their first argument, and return an error as their last result. This requires adding an unnecessary anonymous function for cases where there's no context or error support.
Describe the solution you'd like
It should be possible to do this:
type Foo struct{ ... }
func New() *Foo { .. }
func (*Foo) Start() { .. }
fx.Annotate(New, fx.OnStart((*Foo).Start))
// Note: (*Foo).Start is sugar for func(f *Foo) { f.Start() }
Currently, if you feed this into fx.New, this will fail because Foo.Start does not accept a context or return an error.
Describe alternatives you've considered
Write anonymous functions:
fx.Annotate(New, fx.OnStart(func(f *Foo) { f.Start() }))
Is this a breaking change? No
We should probably support all the variations since we want to also support the lifecyle patten.
// *Foo must be provided by New
func (*Foo) Start() {}
fx.Annotate(New, fx.OnStart( (*Foo).Start ))
// honor error from start function, but not context, and New must be provide *Foo
func (*Foo) Start() error {}
fx.Annotate(New, fx.OnStart( (*Foo).Start ))
// honor context from start function, but no error
func (*Foo) Start(context.Context) {}
fx.Annotate(New, fx.OnStart( (*Foo).Start ))
Yeah that sounds right. Make context and error independently optional.
I think this issue is fixed by https://github.com/uber-go/fx/pull/953 which adds support for functions with and without context parameter and error return.