Dagger 2: How to inject Map, Provider<?

2019-05-05 07:13发布

In Dagger 2, is it possible to inject a Map<Class<? extends Foo>, Provider<? extends Foo>>?

Suppose, I have a couple of classes that extends Foo

class Bar extends Foo {
    @Inject Bar() {}
}

class Baz extends Foo {
    @Inject Baz() {}
}

and now I want to create a FooFactory by declaring

class FooFactory {
    @Inject FooFactory(Map<Class<? extends Foo>, Provider<? extends Foo>> providers) {}
}

Can I do this in Dagger 2 with minimal configuration? I've read about Multibinding but I couldn't get it to work.

1条回答
贼婆χ
2楼-- · 2019-05-05 07:52

Answering my own question in accordance to the guidelines.


First, you have to get rid of the wildcard in Provider<? extends Foo>.

Second, you need to declare an annotation for the map key:

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
public @interface FooKey {
    Class<? extends Foo> value();
}

Then, for each implementation of Foo you need to declare in your Module:

@Binds @IntoMap @FooKey(Bar.class)
abstract Foo bindBar(Bar bar)
查看更多
登录 后发表回答