2

Have an interface that needs many implementations to be bound to it. Going for the following design because of many constraints (May not seem good, please ignore the design).

Is it possible to create an injector for another module installed in current module while still running the configure() method for the current module.?

public class CurrentModule extends AbstractModule{


         @Override
         protected void configure() {
                install(new OtherModule());
                final someInterface getInstance = methodToGetInstance();
                bind(SomeInterface.class).to(getInstance);

         }


         public SomeInterface methodToGetInstance() {
          Injector injector = Guice.createInjector(new OtherModule());
          return new ClassImplementingSomeInterface(injector.getInstance(dependency)); 
       }
}

1 Answer 1

1

Yes, what you ask is possible with provider methods. This is how you should do it:

class CurrentModule extends AbstractModule {

  @Override protected void configure() {
    install(new OtherModule());

    // Optional, but it's good to write it if the dependency becomes missing from OtherModule.
    requireBinding(DependencyFromOtherModule.class);
  }

  @Singleton
  @Provides SomeInterface createSomeInterface(DependencyFromOtherModule dependency) {
    return new ClassImplementingSomeInterface(dependency);
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.