jabu
jabu

Reputation: 1

Build a Map with objects that have dependencies

I have an interface:

public interface MyInterface {...}

Each implementation of MyInterface has its own (different) dependencies. Example:

public class MyObjectOne implements MyInterface {
    @Inject ServiceA ...;
    ...
}

public class MyObjectTwo implements MyInterface {
    @Inject ManagerB ...;
    @Inject ProviderC ...;
    ...
}

I could have hundreds of MyInterface implementations. Now I want to create a Map as follow:

Map<String, MyInterface> map = new HashMap<String, MyInterface>();
map.put("key1", new MyObjectOne());
map.put("key2", new MyObjectTwo());
...
map.put("keyn", new MyObjectN());

Unfortunately, this short-circuit Dagger and won't inject anything in MyObjectOne, MyObjectTwo, ... and MyObjectN. Besides, I don't have an ObjectGraph at this point as this code is part of a library/module.

As I was looking for a solution, I came across the MapBinder class in Guice that seems to do what I want. This feature is not available with Dagger.

  1. Can my problem be solved with Dagger?

  2. If not, is MapBinder a feature that could make it into Dagger 2.0?

Cheers and thanks in advance.

Upvotes: 0

Views: 479

Answers (1)

thatsIch
thatsIch

Reputation: 848

First off, it would be a design-flaw having the need to instantiate something yourself. Dependency Injection was made to elevate that problem and the resulting boiler-plate. I personally would have the classes in a module as injects or includes and inject the instances (probably singletons) into that map.

In your case, what you want to inject is a MemberInjector and inject into the member of MyObjectOne etc. With that you can create your own MapBinder easily by iterating over the values of the map.

Upvotes: 0

Related Questions