Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice bind().toInstance() injects already injected members?

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?

like image 530
Daniel Hári Avatar asked Jan 28 '26 20:01

Daniel Hári


1 Answers

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.
like image 78
Daniel Hári Avatar answered Jan 30 '26 12:01

Daniel Hári



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!