-->

Getting rid of Dagger 2 warning “Generating a Memb

2020-06-07 07:12发布

问题:

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?

回答1:

As of Dagger 2.9 these warnings are off by default.



回答2:

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