27
votes

Given the following classes

abstract class AbstractClass {
    @Inject SomeDependency someDependency;
}

class SomeClass extends AbstractClass {
    @Inject AnotherDependency anotherDepenency;

    public void onCreate() {
        component = // Get component instance somehow
        component.inject(this);
    }
}

in Dagger 2 when injecting dependencies into a class which extends from an abstract base class which also contains dependencies, Dagger shows a warning of the kind Generating a MembersInjector for AbstractClass. Prefer to run the dagger processor over that class instead. during compilation.

However if I override/implement onCreate() in AbstractClass and call the dependency injection there, too, the dependency someDependency will be injected twice which might lead to unexpected behaviour. Once in onCreate() of AbstractClass and once in onCreate() of SomeClass.

What is the best solution to get rid of this warning while preventing duplicate injection of dependencies?

2

2 Answers

3
votes

As of Dagger 2.9 these warnings are off by default.

1
votes

Solution could be: define onCreate() in Abstract class only