Injecting Collection of Classes with Guice

Scruffers picture Scruffers · Dec 10, 2010 · Viewed 14.1k times · Source

I'm trying to inject things with Google Guice 2.0 and I have the following structure:

FooAction implements Action
BarAction implements Action

I then have an ActionLibrary with the following constructor:

ActionLibrary (List<Action> theActions)

When I request an instance of ActionLibrary from Guice, I would like Guice to identify both of the registered Action classes (FooAction, BarAction) and pass them into the constructor. The motivation here being that when I add a third action BazAction, it would be as simple as registering it in the Module and it would automatically be added to the list in the constructor.

Is this possible?

Answer

ColinD picture ColinD · Dec 10, 2010

What you want for this is Multibindings. Specifically, you want to bind a Set<Action> (not a List, but a Set is probably what you really want anyway) like this:

Multibinder<Action> actionBinder = Multibinder.newSetBinder(binder(), Action.class);
actionBinder.addBinding().to(FooAction.class);
actionBinder.addBinding().to(BarAction.class);

Then you can @Inject the Set<Action> anywhere.