javadynamicdependency-injectionguiceguice-3

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


Solution

  • 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.