Search code examples
gwtdependency-injectiongwt-gin

GWT-GIN Multiple Implementations?


I have the following code

public class AppGinModule extends AbstractGinModule{
    @Override
    protected void configure() {
        bind(ContactListView.class).to(ContactListViewImpl.class);
        bind(ContactDetailView.class).to(ContactDetailViewImpl.class);
    }
}

@GinModules(AppGinModule.class) 
public interface AppInjector extends Ginjector{
    ContactDetailView getContactDetailView();
    ContactListView getContactListView();
}

In my entry point

AppInjector appInjector = GWT.create(AppGinModule.class);
appInjector.getContactDetailsView();

Here ContactDetailView is always bind with ContactsDetailViewImpl. But i want that to bind with ContactDetailViewImplX under some conditions.

How can i do that? Pls help me.


Solution

  • You can't declaratively tell Gin to inject one implementation sometimes and another at other times. You can do it with a Provider or a @Provides method though.

    Provider Example:

    public class MyProvider implements Provider<MyThing> {
        private final UserInfo userInfo;
        private final ThingFactory thingFactory;
    
        @Inject
        public MyProvider(UserInfo userInfo, ThingFactory thingFactory) {
            this.userInfo = userInfo;
            this.thingFactory = thingFactory;
        }
    
        public MyThing get() {
            //Return a different implementation for different users
            return thingFactory.getThingFor(userInfo);
        }   
    }
    
    public class MyModule extends AbstractGinModule {
      @Override
      protected void configure() {
          //other bindings here...
    
          bind(MyThing.class).toProvider(MyProvider.class);
      }
    }
    

    @Provides Example:

    public class MyModule extends AbstractGinModule {
        @Override
        protected void configure() {
            //other bindings here...
        }
    
        @Provides
        MyThing getMyThing(UserInfo userInfo, ThingFactory thingFactory) {
            //Return a different implementation for different users
            return thingFactory.getThingFor(userInfo);
        }
    }