Refactor dependecy injection of 32 classes that extend the same abstract class with Dagger

Viewed 186

I'm working on a project with Vert.x that uses Dagger for DI, and there's a class that's creating an unsustainable problem with how big the injection is done.

This is the class that I have:

public class ClassManager {
    private List<ParentClass> all = new ArrayList<>();

    @Inject
    public ClassManager(ParentClass... classes) {
        if (classes != null) {
            all.addAll(Arrays.asList(classes));
        }
    }
    //other methods down here
}

The problem being that, as of right now, we have 32 classes that extend from this abstract class ParentClass, so the injection right now is as this:

    @Provides
    @Singleton
    public ClassManager provideClassManager(SubClassA a, SubClassB b, SubClassC c.... and so on) {
         return new ClassManager(a, b, c...and so on);
    }

I haven't found so far a better solution on how to do this injection with Dagger, but I do need that this ClassManager has access to all of the classes that extend from ParentClass. Is there any other better way? Maybe with other library?

1 Answers

You can use dagger multibindings and bind your subclasses into set, like this

@Module
public abstract class SubClassModule {

    @Binds
    @IntoSet
    public abstract ParentClass bindsSubClassA(impl: SubClassA);

    @Binds
    @IntoSet
    public abstract ParentClass bindsSubClassB(impl: SubClassB)
}

And in module with class manager pass set into constructor

@Provides
@Singleton
public ClassManager provideClassManager(Set<ParentClass> set) {
    return new ClassManager(set);
}
Related