My Module:
bind( Translator.class ).to( TranslatorImpl.class ).in( Scopes.SINGLETON );
Now I expect to get the same instance everytime when I do
Injector injector = ...;
injector.getInstance( Translator.class );
But if I do
injector.getInstance( TranslatorImpl.class );
I get a new instance everytime. Is this a bug or expected behaviour ?
This is the expected behaviour because TranslatorImpl.class
isn't bound to the singleton scope, only Translator.class
is.
If you want both getInstance(..)
to return the same instance, you could bind the implementation to the singleton scope:
bind(Translator.class).to(TranslatorImpl.class);
bind(TranslatorImpl.class).in(Scopes.SINGLETON);
assertEquals(injector.getInstance(Translator.class), injector.getInstance(TranslatorImpl.class));
See https://github.com/google/guice/wiki/Scopes#applying-scopes for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With