强制在匕首中实例化相关对象

时间:2018-02-01 19:09:53

标签: android dagger-2 dagger

我有一个dagger模块来提供一个实例:

@Binds
abstract MyInterface provideMyInterface(MyInterfaceImpl impl);

当创建MyInterfaceImpl的实例时,我还想自动实例化另一个类的实例。让我们称之为MySupportingInstance

如何在实例化MySupportingInstance时确保MyInterfaceImpl也被实例化。我可以在MySupportingInstance中注入MyInterfaceImpl来实现此目的。但后者不使用引用,因此它注入并且不使用引用很奇怪。

我的模块有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以向对象添加范围,它会强制匕首在内部保存引用,然后执行

@Provides
public static MyInterface provideMyInterface(
    MyInterfaceImpl impl, MySupportingInstance instance) {
  // Forced to create an instance of MySupportingInstance, but returning just
  // MyInterfaceImpl.
  // If objects are scoped, instance, once created, will be hold internally by
  // Dagger.
  return impl;
}