1

My core application is complete. I am able to successfully load modules but I still cant properly use guice to inject dependencies in my modules. My core app loades modules using service loader and installs them using the install method of guice's AbstractModule. Here is a sample code:(Simplified)

 @Override
protected void configure() {
    ServiceLoader<IModule> modules = ServiceLoader.load(IModule, ucl);
    for (IModule module : modules) {
        install(module);
    }

} 

Each module implements the IModule interface which extends the Module interface of guice. What confuses me is how can I provide the plug in instances (for example an instance of view) when it is not advised to have injectors all over the place. I read about the @Provides annotation and I think it is a possible solution but another problem I face is that some of them have dependencies that need injecting. For example my pluginview injects an instance of plug in controller. Given this scenario I am unsure on how to use the provider interface. Suggestions will truly be appreciated

public PlugIn implements IModule{
    @Override
    public void configure(Binder binder){
        binder.bind(View.class).to(PlugInView.class);
    }

    public View getView(){
        //Should return a view instance
        //Still unsure how to provide this
    }
}

public PlugInView extends View{

   @Inject
   private PlugInView(PlugInController controller){
   //Do stuff with controller
   }
}
MykelXIII
  • 1,085
  • 1
  • 8
  • 16

1 Answers1

1

Well I finally found out why my approach would not work. After reading around it seems in order for guice to inject dependencies guice has to be the one who instantiates your classes. In my approach, I have an iterator that lazily instantiates the modules loaded by the service loader. In order to fix that I have instead stopped installing modules from my core app.

@Override
protected void configure() {
    ServiceLoader<IModule> modules = ServiceLoader.load(IModule, ucl);
    bind()...//Configure core app bindings

    //Removed this part
    for (IModule module : modules) {
        install(module);
    }
    //Until here
} 

And have each plug in make their own injectors in order to invoke their own configure methods. This approach seems to give each module independent injectors which in my opinion seems acceptable as I want each module to be independent. I also like how this approach allows my plug ins to no longer implement the Module interface or extend the AbstractModule giving them freedom on choosing whether to use guice or not.

MykelXIII
  • 1,085
  • 1
  • 8
  • 16