具有混合作用域的 Dagger2 模块

Dagger2 modules with mixed scopes

我目前正在尝试使用子组件为自定义作用域设置 dagger2,但我在使用 dagger 编译器时遇到了一些问题。更具体地说,我有以下设置:

  @Qualifier @interface Foo {}
  @Qualifier @interface Baz {}
  @Scope @interface SomeScope {}

  @Module
  static class Amodule {
    @Provides
    @SomeScope
    @Foo
    String provideFoo(@Baz String baz) {
      return "foo" + baz;
    }

    @Provides
    @Baz
    String provideBaz() {
      return "baz";
    }
  }

  @Component(modules = Amodule.class)
  interface Acomponent {  
    @Baz String baz();
    Subcomp subcomp();
  }

  @SomeScope
  @Subcomponent
  interface Subcomp {
    @Foo String foo();
  }

不幸的是,这给了我错误:

Acomponent (unscoped) may not reference scoped bindings:
  @Component(modules = AModule.class)
  ^
      @Provides @SomeScope @Foo String Amodule.provideFoo(@Baz String)

我已经通过将所有自定义范围绑定拆分到一个单独的模块中来设法让事情正常进行,但我不确定为什么上面的设置不可行。另外,就我而言,Foo 和 Baz 对象密切相关,因此如果可以避免,我宁愿不将它们拆分为单独的模块。

谁能解释一下为什么 dagger 编译器不接受上面的例子?似乎 @SomeScope 子组件内部应该是公开 @Foo 绑定的有效位置。我是不是误解了什么,或者这可能是代码生成方式的限制?

谢谢

您遇到的错误与您的子组件无关。

您需要将 Acomponent 设置为 @SomeScope。您不能提供与无范围组件不同的范围。 documentation 状态:

Since Dagger 2 associates scoped instances in the graph with instances of component implementations, the components themselves need to declare which scope they intend to represent. For example, it wouldn't make any sense to have a @Singleton binding and a @RequestScoped binding in the same component because those scopes have different lifecycles and thus must live in components with different lifecycles.

添加范围,这应该可以工作。

@SomeScope
@Component(modules = Amodule.class)
interface Acomponent {  
    @Baz String baz();
    Subcomp subcomp();
}