Plugin factory using Multibinder in Guice 3.0?

356 views
Skip to first unread message

fatbrain

unread,
Nov 12, 2011, 2:52:48 PM11/12/11
to google-guice
Hi,

I need to create a new instance of the Plugin each time i call
"createPlugin" on my PluginFactory.

Multibinder<Plugin> plugins =
Multibinder.<Plugin>newSetBinder(binder(), Plugin.class);
plugins.addBinding().to(A.class);
plugins.addBinding().to(B.class);
...

bind(PluginFactory.class).to(PluginFactoryImpl.class);

Where my PluginFactoryImpl is:

@Inject Set<Plugin> plugins;

public Plugin createPlugin(String name) {
... goes through the 'plugins' and return the one which match the
name.

The problem here is of course that the plugins-set is created on
injection-time, so next time createPlugin is called with the same name-
argument I will get a reference to the same instance as before. I need
a "new" instance.

I use my factory like this (which gives me same old instance all the
time):

public class MyApp {
@Inject PluginFactory factory;

public Plugin execute(String name) {
factory.createPlugin(name).execute();
}
}

How would one go about doing something like that?

Cheers,
Jonas

Thomas Broyer

unread,
Nov 12, 2011, 3:20:12 PM11/12/11
to google...@googlegroups.com
How about using a MapBinder and injecting a Map<String, Provider<Plugin>>? That way, you could get the Provider<Plugin> from the map for a given name, and then get a new Plugin instance by calling the Provider's get().

fatbrain

unread,
Nov 12, 2011, 3:46:35 PM11/12/11
to google-guice
Thanks!

You're the best! That solved my problem :).

Cheers,
Jonas
Reply all
Reply to author
Forward
0 new messages