Search code examples
javadependency-injectiondagger-2dagger

Inject all implementations of an interface using Dagger


I have an interface BaseProcessor and several implementations of it.

Now, in a class (ValidationComponent) I want to have a list of all my BaseProcessor implementations, like this : List<BaseProcessor> processors;

All the implementations have an @Inject constructor.

Now, currently I am doing this : In 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);
    }

In order to pass the implementation into the constructor, dagger is creating instances of these implementations because, as mentioned, they all have @Inject constructors.

Now, instead of passing each concrete implementation in the constructor, can I somehow use Dagger to create all of these implementation instances for me?

I know that it is possible in the Spring framework by annotating implementations with @Component spring annotation. Is there a way in Dagger?


Solution

  • You can accomplish this with multibindings, specifically by adding an @IntoSet binding in an abstract module.

    @Module
    abstract class ProcessorBindingModule {
    
        @Binds
        @IntoSet
        abstract BaseProcessor bindProcessor1(ProcessorImpl1 processor);
    
        // ...
    
    }
    

    This makes Set<BaseProcessor> available for injection:

        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
        }