链式依赖项上的 Dagger 2 注入

Dagger 2 injection on chained dependencies

很抱歉只能提供伪代码。我在我的一个 android 项目中使用 Dagger 2,当存在链式依赖项时我遇到了一些麻烦,例如 "A as a B and B has a C" 如下所示:

class A {
  @Inject B b;

  void bootstrap() {
    componentA.inject(this);
  }
}

class B {
  @Inject C c;
}

我的模块和组件如下所示:

moduleA {
  provides B; 
  provides C;
}

componentA {
  void inject(A);
}

但是,当 运行 应用程序时,C 未被注入,因此在引用时给我一个空指针异常。

我的问题是:为什么不注入C?

我试过在 B 中使用 bootstrap 方法并显式将组件 A 注入 B,如下所示:

class B {
   @Inject C c;

   void bootstrap() {
     componentA.inject(this);
   }
}

它有效,但我觉得它不合适,因为我希望 dagger 2 为我找出依赖关系,而不是沿着链传递 componentA。任何帮助,将不胜感激!

如果您不想沿链传递组件 A,则必须在提供的 类.

中使用构造函数参数而不是 @Inject
@Module
public class ModuleA {
    @Singleton
    @Provides
    public A a(B b) {
        return new A(b);
    }

    @Singleton
    @Provides
    public B b(C c) {
        return new B(c);
    } 

    @Singleton
    @Provides
    public C c() {
        return new C();
    } 
}