Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

We had similar requirement once, so what we did was use a factory pattern and add all the implementations in factory class implementation using spring.

That ways, when on run time we would know which implementation to use, we would make a call to my factory to provide implementation class.

Also, anytime you have more implementations you could update spring configuration for factory class.

This may not be close to design you have in mind, but this solved the purpose for us.

Cheers !!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top