Comment by [email protected]:

I'm a bit confused about the behaviour of using Provider and @Singleton simultaneously.

I tried to use a TransactionLogProvider to supply an instance of FileTransactionLog which is annotated with @Singleton. But multiple instances are still instantiated.

Please refer to the snippets below. Two instances of FileTransactionLog would be created, which means @Singleton doesn't work for this scenario.

BillingModule.java
{{{
  protected void configure() {
    bind(TransactionLog.class).toProvider(TransactionLogProvider.class);
    //singleton only works if it's explicitly declared as following
//bind(TransactionLog.class).toProvider(TransactionLogProvider.class).in(Singleton.class);
  }

}}}

TransactionLogProvider.java
{{{
  public TransactionLog get() {
    return new FileTransactionLog();
  }
}}}

FileTransactionLog with @Singleton
{{{
@Singleton
public class FileTransactionLog implements TransactionLog {
  public FileTransactionLog() {
    System.out.println("new FileTransactionLog instance");
  }
}
}}}

Bootstrap
{{{
  public static void main(String[] args) {
    Injector injector = Guice.createInjector(new BillingModule());

    injector.getInstance(RealBillingService.class);
    injector.getInstance(RealBillingService.class);
  }
}}}

For more information:
http://code.google.com/p/google-guice/wiki/Scopes

--
You received this message because you are subscribed to the Google Groups 
"google-guice-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/google-guice-dev?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to