bineanzhou / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 0 forks source link

singleton scope should apply to the value as well as the key #180

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago

This may well be a bad idea, but I wanted to get it out there for discussion.

Several times now I've done this:

class MyModule {

   public void bind() {
      bind(MyInterface.class).to(MyImplementation.class).in(SINGLETON);
   }

}

class SomeWiringHelperOrSomething {

   @Inject
   public void connect(MyImplementation thisThing, SomeClass toThatThing) {
      // ...
   } 
}

Of course, I end up with multiple instances of MyImplementation, because I
*should* have done this:

   bind(MyImplementation.class).in(SINGLETON);
   bind(MyInterface.class).to(MyImplementation.class).in(SINGLETON);

I've seen a few other people do this as well-- everyone at work who's
worked with Guice, actually-- and it's pretty perplexing until you realize
you're looking at different instances of MyImplementation.

That being the case, can SINGLETON be made a special scope, in that binding
a key in SINGLETON implicitly binds the value in SINGLETON as well?  I have
yet to run into a case where I didn't want that to happen.

Original issue reported on code.google.com by logan.jo...@gmail.com on 7 Feb 2008 at 5:49

GoogleCodeExporter commented 9 years ago
It turns out that scoping the second binding doesn't do anything. You could 
also do this to get the desired 
behaviour:
   bind(MyImplementation.class).in(SINGLETON);
   bind(MyInterface.class).to(MyImplementation.class);

There's a few cases where this behaviour isn't what you want. For example, if 
the keys are annotated:
   bind(DataAccess.class).in(SINGLETON);
   bind(DataAccess.class).to(SqlDataAccess.class);
   bind(DataAccess.class).annotatedWith(WithPrivateCache.class).to(SqlDataAccess.class);

Regardless, although this might be a nice feature, we're stuck with the current 
behaviour.

Original comment by limpbizkit on 14 May 2008 at 3:40