0

I have two interfaces A and B and B is extending A.

I have one provider being able to provide instances whose Class is implementing B (and consequently A).

I would like to bind Provider to B.class (straightforward) and to A.class with an Annotation in a singleton scope.

bind(B.class).toProvider(MyBImplProvider.class).in(Scopes.SINGLETON); bind(A.class).annotatedWith(Names.named("B")).toProvider(MyBImplProvider.class).in(Scopes.SINGLETON); 

How to return the same instance from the provider no matter if I inject through B.class or through A.class+Annotation. For instance, I'd like to be able to define constuctors as

@Inject C(B param) 

or

@Inject C(@Named("B") param) 

In both case, I'd like param to be valuated with the same singleton.

1 Answer 1

3

How about making your A Provider depend on the B provider you've defined above?

@Provides @Named("B") A provideA(Provider<B> bProvider) { return bProvider.get(); } 

That should work since you said B extends A. You might need to play around with the @Named bit.

Another option would be to use a toInstance(yourObject) binding. But this makes it messy to inject any dependencies into that object. You would have to use Binder#requestInjection().

Sign up to request clarification or add additional context in comments.

2 Comments

I don't have it. Will Guice inject the Provider<B> ?
Yes it will. Try it? (The method has to go on a Guice module, see @Provides methods)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.