uber-go/fx

How to inject implementation via interfaces using fx.In ?

iangregsondev opened this issue · 4 comments

Hi,

Can anyone help which would allow me to inject an implementation via an interface but using "fx.In" ?

Quite confused and it seems there may be an issue when using "fx.In".

Maybe I am just not looking in the right place but i just can't seem to figure it out. Here is an example of what I am trying to do

I have an implementation of an interface named "Pool" i.e.

Here is the interface Pool

type interface Pool {
 // .... various common methods that NewMempool (below) implements
}

and the implementation (there will be a few).

func (receiver *DI) providePool() fx.Option {
	return fx.Options(
		fx.Provide(mempoolinfo.NewMempool), /// notice this is the implementation and NOT the interface - this can't be right..

And here is the Params that are created elsewhere and injected into a "new" constructor somewhere i.e.

type Params struct {
	fx.In
	Pool *pool.Pool /// Notice here is the interface - i want to inject an interface - is this the right way ?
}

func New(params Params) *Item {
	return &Item{ ..........................

I tried getting some kind of a good tutorial and googled it :-) But I just can't find any help.

I would appreciate any pointers or small example someone can offer

Thanks.

So you can do this in fx, just not using fx.In structs. You can inject a type as an interface type by using fx.As.

There are some examples of how to do this in the documentation.

Thanks, @sywhang , so I just need to pass in each type into the New constructive rather than using fx.in construct, maybe I could use the fx.In for all NON-interface injections and inject the interfaces without an fx.In - or maybe this is not a good practice ?

Is the fx.In going to be supported in the future?

Actually, I hadn't always used the fx.In BUT since I have been doing it, it's tidied things up quite a bit.

Thanks in advance.

There is no plans in flight to support injecting an interface using fx.In yet.

So fx.Annotate was added as a syntactic sugar that allows you to inject without using fx.In structs.

It actually covers everything you can do with fx.In like making something an optional argument, named argument, or part of a value group. You can also use it with fx.Supply: https://pkg.go.dev/go.uber.org/fx#Annotate. fx.As also works with fx.Supply.