3.0: Assisted Inject and MapBinder

563 views
Skip to first unread message

kimchy

unread,
Jan 10, 2011, 11:22:46 AM1/10/11
to google...@googlegroups.com
Hi,

  Wondering how to use the new assisted inject with MapBinder, now that FactoryProvider is deprecated? For example, how to code this: mapBinder.addBinding(name).toProvider(FactoryProvider...) ?

cheers,
-shay.banon

Fred Faber

unread,
Jan 10, 2011, 11:41:25 AM1/10/11
to google...@googlegroups.com
To solve this you're able to bind the Factory using FactoryModule builder, and then add it to the map.

class Car {
  @Inject Car(@Assisted Color color) { ...}

  interface CarFactory {
     Car create(Color color);
  }
}

And let's say you want a map that gives you:
 "green" => new Car(Color.GREEN)
 "blue" => new Car(Color.BLUE)

install(new FactoryModuleBuilder().
   .build(Key.get(CarFactory.class, Names.named("CreatesGreenCars"));


install(new FactoryModuleBuilder().
   .build(Key.get(CarFactory.class, Names.named("CreatesBlueCars"));

MapBinder<Color, CarFactory> mapBinder =
  MapBinder.newMapBinder(binder(), Color.class, CarFactory.class);
mapBinder.addBinding(Color.GREEN)
  .to(Key.get(CarFactory.class, Names.named("CreatesGreenCars"));
mapBinder.addBinding(Color.BLUE)
  .to(Key.get(CarFactory.class, Names.named("CreatesBlueCars"));

That will give you what you're looking for, I believe.

There's some boilerplate that a method or two could reduce e.g., Key getKey(Color color) { ...}

-Fred


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

Fred Faber

unread,
Jan 10, 2011, 12:05:04 PM1/10/11
to google...@googlegroups.com
Actually, my initial example was a bit different than the one I wrote.

I don't see a reason to create the different bindings for the Factories.  Just add a single binding, then use it as values for several entries in the map.

Fred

Leigh Klotz

unread,
Jan 13, 2011, 7:17:54 PM1/13/11
to google-guice
This thread might help:
<http://groups.google.com/group/google-guice/browse_thread/thread/
7f51af1f3860205d/bf1fff0b4dd4dbad#bf1fff0b4dd4dbad>

Reply all
Reply to author
Forward
0 new messages