On Wed, Jul 23, 2008 at 12:25 PM, Sam Berlin <sbe...@gmail.com> wrote:
> Hi Folks,
>
> I'm attempting to use the hierarchical injectors, but it doesn't seem
> to be working like I thought it would. Is the following use-case
> supported? ...
>
> ---
>
> Injector parent = Guice.createInjector(new AbstractModule() {
> public void configure() {
> bind(Foo.class).to(FooImpl.class);
> }
> });
>
> Injector child = Guice.createInjector(parent, new AbstractModule() {
> public void configure() {
> bind(Bar.class).to(BarImpl.class);
> }
> });
>
> interface Foo {}
> class FooImpl implements Foo {}
>
> interface Bar {}
> class BarImpl implements Bar {
> @Inject Foo foo;
> }
>
> -----
>
> In a nutshell -- can the child have injections that are bound from the
> parent? I had thought this was a purpose, but in my attempts, I keep
> getting an error:
>
> com.google.inject.CreationException: Guice configuration errors:
>
> 1) Error at org.limewire.inject.AbstractModuleTest$BarImpl.foo(AbstractModuleTest.java:61):
> No implementation for org.limewire.inject.AbstractModuleTest$Foo was bound.
>
> 1 error[s]
> at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:324)
> at com.google.inject.InjectorBuilder.validate(InjectorBuilder.java:168)
> at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:99)
> at com.google.inject.Guice.createInjector(Guice.java:139)
> at com.google.inject.Guice.createInjector(Guice.java:126)
> [...]
>
> Thanks much,
> Sam
>
My actual error cropped up because the parent injector was binding
using AssistedInject, so it was binding a provider. When I added
in(Scopes.SINGLETON) to the provider binding, the hierarchical error
disappeared. That seems a little counter-intuitive, as it shouldn't
matter whether or not the provider is a singleton.
Is there some technical limitation to hierarchical injectors that
requires the bindings to needed bindings to be singletons? It would
be better, IMO, if the child injectors worked simply as an extension
to the parent injector.
My use case is that I'm investigating the feasibility of using Guice
for our UI, in addition to the core. The core needs to be constructed
early on, initialized, and checked for consistency. The UI needs to
be constructed in the Swing thread (otherwise Swing breaks -- it needs
all classes constructed in its thread). This would seem to be a prime
candidate for hierarchical injectors -- build the core, then build the
UI which requires the core.
Sam
Sam