我有这个 AppModule
类,其中包含三个函数:
@Singleton
@Provides
static FirebaseFirestore provideFirebaseFirestore() {
return FirebaseFirestore.getInstance();
}
@Singleton
@Provides
static CollectionReference provideUsersCollRef(FirebaseFirestore db) {
return db.collection("users");
}
@Singleton
@Provides
static CollectionReference provideBarsCollRef(FirebaseFirestore db) {
return db.collection("bars");
}
我读到可以使用某种命名,但我没有找到任何方法来解决这个问题。除此之外,我如何在 fragment 代码中区分我注入(inject)的是哪一个引用?提前致谢。
编辑:
@Inject
@Named("bars")
BarsDataSource(CollectionReference barsRef) {
this.barsRef= barsRef;
}
最佳答案
这是正确的。 dagger2 无法决定提供哪一个,对吧?
一个可能的解决方案是使用@Named
注释。您还必须在@Inject 中命名它们。例如。
@Named("users")
@Singleton
@Provides
static CollectionReference provideUsersCollRef(FirebaseFirestore db) {
return db.collection("users");
}
@Named("bars")
@Singleton
@Provides
static CollectionReference provideBarsCollRef(FirebaseFirestore db) {
return db.collection("bars");
}
和
@Named("bars")
@Inject
public CollectionReference bars;
或者使用构造函数注入(inject)
@Inject
BarsDataSource(@Named("bars") CollectionReference barsRef) {
this.barsRef= barsRef;
}
关于android - Dagger 不允许我在一个类中使用两个相同类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463339/