guice: @Inject Injector does not work with child injectors
The testcase below works, if the injector is created by:
Guice.createInjector(new ChildModule());
it fails if the injector is created by:
Guice.createInjector().createChildInjector(new ChildModule());
The error is:
com.google.inject.ConfigurationException: Guice configuration errors:
- Unable to create binding for guice.GuiceTest$IOne. It was already configured on one or more child injectors or private modules bound at guice.GuiceTest$ChildModule.configure(GuiceTest.java:39) If it was in a PrivateModule, did you forget to expose the binding? while locating guice.GuiceTest$IOne
package guice;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
public class GuiceTest {
public interface IOne {
}
public static class One implements IOne {
}
public interface ITwo {
IOne getOne();
}
public static class Two implements ITwo {
@Inject Provider<Injector> provider;
@Override
public IOne getOne() {
return provider.get().getInstance(IOne.class);
}
}
public static class ChildModule extends AbstractModule {
@Override
protected void configure() {
bind(IOne.class).to(One.class);
bind(ITwo.class).to(Two.class);
}
}
@Test
public void thisTestWorks() {
Injector injector = Guice.createInjector(new ChildModule());
ITwo two = injector.getInstance(ITwo.class);
assertNotNull(two.getOne());
}
@Test
public void thisTestFails() {
Injector injector = Guice.createInjector().createChildInjector(new ChildModule());
ITwo two = injector.getInstance(ITwo.class);
assertNotNull(two.getOne());
}
}
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 6
- Comments: 18 (6 by maintainers)
Commits related to this issue
- Update documentation to elaborate on how hierarchical modules change the importance of otherwise unnecessary binding statements. Closes #973, a documentation alternative to #1337. PiperOrigin-RevId:... — committed to google/guice by sameb a year ago
- Update documentation to elaborate on how hierarchical modules change the importance of otherwise unnecessary binding statements. Closes #973, a documentation alternative to #1337. PiperOrigin-RevId:... — committed to google/guice by sameb a year ago
@sameb, that does, indeed, seem to be the bug - instances obtained through child injectors are handed the parent injector in some (but not all) cases:
Any chance this bug will get addressed?
So, the weird workaround that someone at my company seems to have figured out is that if you inject an injector along with something exclusively from the parent injector scope, the right injector gets injected.
heres an SSCCE: