Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic dependency injection

I want to achieve DYNAMIC dependency injection. Does GUICE support this? If not could you recommend any other DI framework?

The implementation that should be used for injection via @Inject must be determined during runtime e.g. via interaction with the user.

Similar to these questiones: http://www.panz.in/2008/12/dynamic-dependency-injection.html http://www.panz.in/2008/12/dynamic-dependency-injection.html

Thank you

like image 898
Georg Heiler Avatar asked May 23 '26 06:05

Georg Heiler


1 Answers

The implementation needs to vary based on input, at some point you're going to have to resolve the input into some kind of class.

If you want that mapping to live in Guice, then you're basically getting an implementation based on a parameter, which maps to the SO question I just answered here. You can write a small injectable class that takes the input and returns a fully-injected implementation.

If you already have that mapping and have (for instance) a class literal in a variable, then you can just inject an Injector directly and ask it for the implementation.

class YourClass {
  @Inject Injector injector;

  SomeInterface yourMethod(String input) {
    Class<? extends SomeInterface> clazz = getClassLiteralFromInput(input);
    return injector.getInstance(clazz);
  }

  Class<? extends SomeInterface> getClassLiteralFromInput(String input) {
    // Implement this as needed.
    return SomeInstance.class;
  }
}

Note that while you can always inject an Injector, you should only do so when you really don't know what kind of implementation you need (like here). In general you should inject the SomeInstance itself, or a Provider<SomeInstance> if you want to delay the creation.

like image 52
Jeff Bowman Avatar answered May 26 '26 09:05

Jeff Bowman



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!