android - Dagger 不允许我在一个类中使用两个相同类型的对象

标签 android dependency-injection dagger-2 dagger

我有这个 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/

相关文章:

java - 在 Activity 之外注入(inject)时如何使用 Dagger2 排列组件?

java - 如何将附加纹理链接到着色器中。 LibGDX

java - Android - 错误线程和按钮仍然可点击

android - 在arcore中绘制到相机中心的垂直线

java - 了解 Dagger2 流程(提供的示例)

android - 在 Dagger Dialog Fragment 中使用 View Model Providers(ViewModelProviders)

Android框架源码中启用Fast Scroll的Android Listview代码

php - 带有条件消息的 Laravel 自定义表单验证

angular - 测试依赖于服务的管道

android - Dagger 2 在 Kotlin 对象中注入(inject)上下文