On Sun, Jun 6, 2010 at 12:20 AM, Tim Boudreau <[email protected]> wrote:

> I have a codebase with several layers of SPI in separate projects -
> we'll call this these projects SPI (minimal interfaces), SPISupport
> (convenience implementations of some common logic - in practice there
> is yet another layer that ties you to some specific data storage
> choices but simplifies things further).  A frequent pattern is:
>  - SPI contains "interface A" and "class Something { @Inject A a; ..."
>  - SPISupport contains "abstract class AbstractA implements A" and
> "final class HelperClass { @Inject AbstractA a; ..."
>  - TestHarness contains "ReferenceImplementation extends AbstractA {"
>
> A test implementation then extends AbstractA over a HashMap - a thing
> that really *has* to be a singleton with respect to the module that
> creates it (but using a static would make it possible for unit tests
> to cause side effects for each other).
> bind (A.class).to(AImpl.class).in(Scopes.SINGLETON);
> bind (AbstractA.class).to(AImpl.class).in(Scopes.SINGLETON);
>
> Rather surprisingly, *two* instances of AImpl are created - so far I
> have found no clean way to avoid this.  Since SPI cannot know about
> classes in SPISupport, this is rather a impasse.
>

Just add:

bind(AImpl.class).in(Scopes.SINGLETON);

Before the other two bindings. That will solve your problem.

Explanation:
All bindings in Guice are transitive and resolved by key, so a A ->
singleton bound to non-singleton AImpl, Similarly AbstractA -> singleton
bound to (different instance of) non-singleton AImpl. If you bind AImpl as a
singleton, then both A and AbstractA simply point to the binding of AImpl,
which is the same singleton.

Dhanji.

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

Reply via email to