Question

I have an Injector instance a, and I'd like to create another Injector b which does the same as a, except for two bindings, which get overridden by the Module I provide. Is this possible?

I know about Modules.override, but that does not take an Injector as argument. If it was possible to convert an Injector to a Module, that would solve my problem.

Was it helpful?

Solution

The simplest way of thinking about this would be through child injectors, but that is explicitly disallowed as a design decision:

The reason overriding a binding in a child injector isn't supported is because it can lead a developer towards writing code that can work in either a parent & child injector, but have different behavior in each. This can lead to very surprising scenarios, because of just-in-time (JIT) bindings and the way they interact with parent/child injectors.

At this point, I would probably think about restructuring your application to avoid requiring these complicated bindings, but if you want to go further, you can probably use Injector.getBindings() or Injector.getAllBindings() (note the difference!) and stitch them back into a module using the Elements SPI. After all, Binding<?> extends Element, and Elements.getModule(...) will create a Module from your Elements. I haven't checked that it works, but that's probably your best lead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top