2

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?

Mangu
  • 3,160
  • 2
  • 25
  • 42
  • Have you tried using the dagger verticle factory approach? It's described [here](https://medium.com/@michel.werren/dependency-injection-in-vert-x-with-dagger-2-7087bc6b9f4f) – Selim Nov 25 '21 at 14:11
  • or just something like [this](https://stackoverflow.com/q/205573/592355)/[that](https://stackoverflow.com/q/347248/592355)? – xerx593 Nov 29 '21 at 15:14

1 Answers1

0

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);
}
Sotin Semyon
  • 131
  • 1
  • 5