The Guice IoC container provides MapBinder, which is often useful.
We’re also using Windsor v3.0 in .NET.
Given the following slightly contrived example, can anybody suggest how Windsor could be used in the same way?
enum Format {
Xml,
Json
}
interface Formatter {
String format(Object o);
}
class XmlFormatter implements Formatter {
@Override
public String format(Object o) {
throw new NotImplementedException();
}
}
class JsonFormatter implements Formatter {
@Override
public String format(Object o) {
throw new NotImplementedException();
}
}
class FormattersModule extends AbstractModule {
@Override
protected void configure() {
MapBinder<Format, Formatter> formattersMapBinder
= MapBinder.newMapBinder(
binder(), Format.class, Formatter.class);
formattersMapBinder.addBinding(Format.Xml).to(XmlFormatter.class);
formattersMapBinder.addBinding(Format.Json).to(JsonFormatter.class);
}
}
class FormattersClient {
private final Map<Format, Formatter> formatters;
@Inject
FormattersClient(Map<Format, Formatter> formatters) {
this.formatters = formatters;
}
public void Format(Format format, Object o) {
String s = formatters.get(format).format(o);
// ... do something with s ...
}
}
public class Main {
private static Injector injector;
public static void main(String[] args) {
injector = Guice.createInjector(new FormattersModule());
FormattersClient formattersClient
= injector.getInstance(FormattersClient.class);
formattersClient.Format(Format.Json, new String("Foo"));
formattersClient.Format(Format.Xml, new String("Foo"));
}
}
So this example is quite straightfoward, if you’re happy to use a string value for the key.