I would strongly discourage making production code aware of wiring
logic. The module is there for this purpose.

Dhanji.

On Thu, Feb 19, 2009 at 5:41 AM, Leigh Klotz <[email protected]> wrote:
>
> If your application is not exactly as described, but slightly more
> complex and you need to map between myAnimal descriptions multiple
> times, not just once, you might consider a Mapbinder.  It's similar to
> your custom provider solution, but eliminates inline if/else code, and
> promotes extension by addition in other modules, since all MapBinder
> additions to a given type pair are shared.
>
> class Barn {
>    @Inject Map<String, Animal> animals;
>    void foo(String name) {
>        Animal animal = animals.get(name);
>        ...
>    }
>
> }
>
> import com.google.inject.multibindings.MapBinder;
>
> class MyModule extends AbstractModule {
>    private void defanimal(MapBinder<String, Animal>m, String name,
> Class<? extends Animal> c) {
>      m.addBinding(name).to(c);
>    }
>
>    public void configure() {
>        MapBinder<String, Animal> m = MapBinder.newMapBinder(binder(),
> String.class, Animal.class);
>        defanimal(m, "cow", Cow.class);
>        defanimal(m, "goat", Goat.class);
>    }
>
> }
>
> Leigh.
>
> On Feb 17, 4:25 pm, Jonathan Dray <[email protected]> wrote:
>> Hi,
>>
>> I'm using Guice for DI in one of my projects.
>> I need to choose the right class to inject depending on the value of a
>> property read in a properties file.
>> Here is a small exemple of what I want to do :
>>
>> Class myFarm {
>>   @Inject
>>   public myFarm(Animal animal) {
>>   }
>>
>> }
>>
>> Now I want that the Animal injected here should be an instance of a
>> "Cow" or a "Goat" (which implements the Animal Interface) mapped from
>> the property "myAnimal" read in my application property file.
>>
>> I thought about two solutions  :
>>
>> 1. use a custom provider to get an animal which takes the value of the
>> property as a parameter.
>> 2. In the configure method of my Guice Module instance, read the
>> property and add a binding depending on the value.
>>
>> Do I have any other alternative with Guice ?
>> Which of these method would you chose in that case ?
>>
>> Thanks for your help.
>> Regards,
>> Jonathan Dray
> >
>

--~--~---------~--~----~------------~-------~--~----~
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=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to