Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injector.getInstance(..) returns a new instance for a singleton

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 ?

like image 977
ashitaka Avatar asked Feb 10 '09 04:02

ashitaka


1 Answers

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.

like image 159
albertb Avatar answered Nov 11 '22 06:11

albertb