views:

513

answers:

1

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 ?

+9  A: 

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 http://code.google.com/p/google-guice/wiki/Scopes#Applying_Scopes for more details.

albertb