3

I have multiple injectors in a multi module project, and want to pass an already injected instance from module A to another Guice module B:

//module B    
bind(DeleteEmployeeUseCaseFactory.class).toInstance(useCaseFactories);
//usecaseFactories comes from module A, and already injected

However this results binding exception in module B as guice tries to re-inject "usecaseFactories" members in moduleB where those dependencies not binded.

Why guice try to inject given instance's members, and how to avoid that?

Daniel Hári
  • 7,254
  • 5
  • 39
  • 54
  • 1
    Can you post more about the exception? Though it's rare to manage multiple injectors manually (compared to creating child injectors), I don't see a reason that what you described shouldn't work. Just remember that modules and injectors are different things, and Guice doesn't care about module dependencies, it cares about injector dependencies. – Jeff Bowman May 22 '16 at 17:52
  • Thanks, my problem is exactly same as described here: https://github.com/google/guice/issues/751. Modules are separated because they encapsulating their inside DI behavior, just communicating through an interface (useCaseFactories in this case). Maybe not the best design, but I don't have an example to make it with child injector while keeping modules independent and clean. – Daniel Hári May 22 '16 at 20:46
  • However I solved my problem with Providers.of(..). – Daniel Hári May 22 '16 at 20:52
  • Sounds like an excellent solution! I learned something new. You may want to link to the big and Auto Injection wiki page as a self-answer. – Jeff Bowman May 22 '16 at 20:59

1 Answers1

3

I solved to avoid injection of instance's already injected members by using Provider:

bind(DeleteEmployeeUseCaseFactory.class).toProvider(Providers.of(useCaseFactories));

However this is guice's expected behavior as decribed here:

Automatic Injection

Guice automatically injects all of the following:

  • instances passed to toInstance() in a bind statement
  • provider instances passed to toProvider() in a bind statement The objects will be injected while the injector itself is being created. If they're needed to satisfy other startup injections, Guice will inject them before they're used.
Daniel Hári
  • 7,254
  • 5
  • 39
  • 54