Comment #5 on issue 369 by [email protected]: Convenient way to expose multibindings and mapbindings from PrivateModules
http://code.google.com/p/google-guice/issues/detail?id=369

Basically, I do this...

public class MyModule extends AbstractModule
{
    private final String m_configurationValue;
    public MyModule(String configurationValue)
    {
        m_configurationValue = configurationValue;
    }

    @Override
    protected void configure()
    {
        MapBinder<String, MessageHandler> mapBinder =
            MapBinder.newMapBinder(binder(), Foo.class, Bar.class);

        // Great, I'm creating an injector in my configure...
        Injector injector = Guice.createInjector(getPrivateModule());

        // We could have bound this to an instance of Bar.class instead,
        // but that would require remote calls in its providers be executed
        // in our unit tests and that would not work correctly. This limits
        // our Module unit testing.
        mapBinder.addBinding(new Foo()).toProvider(
                injector.getInstance(MyBarProvider.class).getProvider());
    }

    // This class exists just to manipulate an injector within Configure
    private static class MyBarProvider {
        private @Inject Provider<Bar> provider;

        public Provider<Bar> getProvider() {
            return provider;
        }
    }

    private Module getPrivateModule()
    {
        return new PrivateModule() {
            @Override
            protected void configure()
            {
                // Bar.class depends on an A provider One, but in other
                // modules depends on A provider two because of different
                // implementations.
                bind(A.class).toProvider(AImplProviderOne.class);
                // Bar.class depends on an B provider Three, but in other
                // modules depends other providers.
                bind(B.class).toProvider(BImplThreeProvider.class);

                // B implementations need a parameter passed into the module
// that indicate something, like initial size or file to read
                // or something.
bind(String.class).annotatedWith(BParameter.class).toInstance(configurationValue);

                bind(bar.class);
                expose(bar.class);
            }
        }
    }
}

--
You received this message because you are subscribed to the Google Groups 
"google-guice-dev" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-guice-dev?hl=en.

Reply via email to