Possible solution to the robot legs problem:
configure() {
Injector leftLeg = Guice.makeInjector(new LegModule(Left.class));
Injector rightLeg = Guice.makeInjector(new LegModule(Right.class));
bind(Leg.class).annotatedBy(@Left).toBindingFrom(leftLeg, Leg.class);
bind(Leg.class).annotatedBy(@Right).toBindingFrom(rightLeg, Leg.class);
}
Each injector acts as a kind of static scope, so this allows us to avoid
getting parts from the "left leg" box connected to parts from the "right
leg" box.
But suppose we have singletons we want to export to the leg modules? How
about this?
configure() {
Module exportToLegs = exportBindings(Torso.class);
Injector leftLeg =
Guice.makeInjector(new LegModule(Left.class), exportToLegs);
Injector rightLeg =
Guice.makeInjector(new LegModule(Right.class), exportToLegs);
bind(Leg.class).annotatedBy(@Left).toBindingFrom(leftLeg, Leg.class);
bind(Leg.class).annotatedBy(@Right).toBindingFrom(rightLeg, Leg.class);
}
The nice thing about this is that any bindings that cross injectors are
explicitly mentioned using imports and exports. I think that's mostly a
feature.
A possible issue is that @Singleton becomes ambiguous. Do you mean
singleton within one injector, or across all connected injectors? Maybe we
need @ReallyASingleton, which will cause Guice to report an error if two
injectors containing an instance of the same singleton are connected into a
single system.
It's also possible that we don't really want linked injectors, but instead
we have a BoundaryModule that doesn't allow bindings to escape from it
unless they're explicitly imported or exported. A BoundaryModule contains
other Modules that can all interlink, but controls all imports and exports
that cross its boundary. Any two BoundaryModules can bind the same key
without conflict because each gets its own set of bindings.
Original issue reported on code.google.com by bslesinsky on 6 Jul 2007 at 3:25
Original issue reported on code.google.com by
bslesinsky
on 6 Jul 2007 at 3:25