I'm writing an application server (
http://dimdwarf.sourceforge.net/)
and just begun using Guice with it. It works as I intended, but there
is one thing which does not fit into my mental model about how the
bindings work:
I have bindings:
bind(EntityLoader.class).to(EntityManagerImpl.class);
bind(ReferenceFactory.class).to(EntityManagerImpl.class);
and a class:
@TaskScoped
public class EntityManagerImpl implements ReferenceFactory,
EntityLoader, TransactionListener { ... }
(The task scope is a custom scope, similar to request scope. A task is
a transactional unit of work.)
In the following code, factory and loader point to the same instance
(factory == loader):
ReferenceFactory factory =
injector.getInstance(ReferenceFactory.class);
EntityLoader loader =
injector.getInstance(EntityLoader.class);
This is as it should be (there must be exactly one EntityManagerImpl
instance per task, because it keeps a list of all entities which have
been loaded in memory), but from the binding configuration it is not
intuitive to me, that _why_ it works this way.
The above bindings appear to be functionally equivalent with the
following bindings (when the @TaskScoped annotation is removed from
the EntityManagerImpl class):
bind(EntityManagerImpl.class).in(TaskScoped.class);
bind(EntityLoader.class).to(EntityManagerImpl.class);
bind(ReferenceFactory.class).to(EntityManagerImpl.class);
But my initial intuition was that it would be equivalent with the
following, which creates two instances of EntityManagerImpl per task:
bind(EntityLoader.class).to(EntityManagerImpl.class).in(TaskScoped.class);
bind(ReferenceFactory.class).to(EntityManagerImpl.class).in(TaskScoped.class);
Is there some documentation which would help me to reach a correct
mental model on how the scopes and bindings are resolved? Is there
some way to print a graph of all the bindings, scopes and instances,
so that I could see how Guice exactly resolves the bindings of a given
module?