使用 Dagger 注入接口的所有实现

Inject all implementations of an interface using Dagger

我有一个接口 BaseProcessor 和它的几个实现。

现在,在 class (ValidationComponent) 中,我想要一个包含我所有 BaseProcessor 实现的列表,如下所示:List<BaseProcessor> processors;

所有实现都有一个 @Inject 构造函数。

现在,我正在这样做: 在 ValidationComponent class,

    private List<BaseProcessor> processors;

    @Inject
    public ValidationComponent(@NonNull final ProcessorImpl1 processor1,
                               @NonNull final ProcessorImpl2 processor2,
                               @NonNull final ProcessorImpl3 processor3) {
        this.processors = new ArrayList<>();
        this.processors.add(processor1);
        this.processors.add(processor2);
        this.processors.add(processor3);
    }

为了将实现传递给构造函数,dagger 正在创建这些实现的实例,因为如前所述,它们都有 @Inject 个构造函数。

现在,我可以使用 Dagger 以某种方式为我创建所有这些实现实例,而不是在构造函数中传递每个具体实现吗?

我知道在 Spring 框架中可以通过使用 @Component spring 注释来注释实现。 Dagger 有办法吗?

您可以在抽象模块中使用 multibindings, specifically by adding an @IntoSet 绑定来完成此操作。

@Module
abstract class ProcessorBindingModule {

    @Binds
    @IntoSet
    abstract BaseProcessor bindProcessor1(ProcessorImpl1 processor);

    // ...

}

这使得 Set<BaseProcessor> 可用于注入:

    private List<BaseProcessor> processors;

    @Inject
    public ValidationComponent(@NonNull final Set<BaseProcessor> processors) {
        this.processors = new ArrayList<>(processors);
        // or just make the field a Set instead of a List
    }