我有一个dagger模块来提供一个实例:
@Binds
abstract MyInterface provideMyInterface(MyInterfaceImpl impl);
当创建MyInterfaceImpl
的实例时,我还想自动实例化另一个类的实例。让我们称之为MySupportingInstance
。
如何在实例化MySupportingInstance
时确保MyInterfaceImpl
也被实例化。我可以在MySupportingInstance
中注入MyInterfaceImpl
来实现此目的。但后者不使用引用,因此它注入并且不使用引用很奇怪。
我的模块有没有办法解决这个问题?
答案 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;
}