0

Guice IoC コンテナーは、しばしば役立つ MapBinder を提供します。また、.NET で Windsor v3.0 を使用しています。次の少し不自然な例を考えると、Windsor を同じように使用する方法を誰か提案できますか?

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"));
    }
}
4

1 に答える 1

0

したがって、キーに文字列値を使用してもよければ、この例は非常に簡単です。

class FormattersInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component
                .For<IFormatter>()
                .ImplementedBy<XmlFormatter>()
                .Named(Format.Xml.ToString()));
        container.Register(
            Component
                .For<IFormatter>()
                .ImplementedBy<JsonFormatter>()
                .Named(Format.Json.ToString()));
    }
}
class Program
{
    static void Main(string[] args)
    {
        var container = new WindsorContainer();
        container.Install(new FormattersInstaller());
        var xmlFormatter = container.Resolve<IFormatter>(Format.Xml.ToString());
        var jsonFormatter = container.Resolve<IFormatter>(Format.Json.ToString());
        // use the formatters...
    }
}
于 2012-06-25T14:08:13.337 に答える