Hello everyone,

I'm new to Guice (really enjoying it, by the way), but have come up
against a need and I'm not sure the most Guice-appropriate way to do
it.  Done a lot of searching (including in this group), but am not
sure I found the solution.  (Or perhaps I just didn't understand it.)
In any case, my question is how to select an implementation based on
some runtime value.  For reference, a standard factory solution would
look like:

class ServiceFactory {
  public static Service get(int type) {
     if(type == 1) { return new ServiceImpl1(); }
     else if (type == 2) { return new ServiceImpl2(); }
  }
}

class Client {
   public void process(int type) {
      Service service = ServiceFactory.get(type);
   }
}

Feels too service locator-y.  But I can think of no way to do this in
Guice except to inject the factory:

class Client {
        @Inject
        ServiceFactory factory;

        public void process(int type) {
                Service service = factory.get(type);
        }
}

class ServiceFactoryProvider implements Provider<ServiceFactory> {
        @Override
        public ServiceFactory get() {
                return new ServiceFactory();
        }
}

class MyModule extends AbstractModule {
        @Override
        protected void configure() {
                bind(Client.class);
        }
}

What am I missing here?  What's the proper way to implement this with
Guice?  I don't think BindingAnnotations will work for me here,
because the implementation is decided upon at runtime, but feel free
to correct me.

Thank you!
Ryan

--

You received this message because you are subscribed to the Google Groups 
"google-guice" 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?hl=.


Reply via email to