Dagger2 在模块中创建接口的重复实例

Dagger2 create duplicate instance of interface in Module

我在带有@ContributesAndroidInjector 注释的应用程序中使用 dagger-android。

@Module
public abstract class ActivityBuilder {
    @ContributesAndroidInjector(modules = BleDevicesModule.class)
    abstract BleDevicesActivity bindBleDevicesActivity();
}
@Module
class BleDevicesModule {

...

@Provides
    fun provideBleObserver(bleRepository: IBluetoothRepository): IObservableUseCase<List<Device>> {
        return GetAllAvailableBleDevicesUseCase(bleRepository)
    }

    @Provides
    fun providePairDeviceUseCase(bleRepository: IBluetoothRepository): ISingleUseCaseWithParameter<Device, Boolean> {
        return ConnectDeviceUseCase(bleRepository)
    }

    @Provides
    fun provideBleRepository(bluetoothManager: BluetoothManager, context: Context,
                                      authorBleScanner: AuthorBleScanner, authProvider: IAuthProvider): IBluetoothRepository {
        return BluetoothRepository(bluetoothManager, context, authorBleScanner, authProvider)
    }
}

我知道我创建了 2 个使用 IBluetoothRepository; 依赖项的用例,因此 provideBleRepository() 方法被调用了两次,每次都会创建一个新的 BluetoothRepository 对象及其所有内容依赖项。如何使存储库对象成为单例?作为一个愚蠢的解决方案,我在 BleDevicesModule 中使用变量,init 和 return 它来自 provideBleRepository() 但我认为必须有更简单的方法

您可以使用 @Singleton

@Provides
@Singleton
fun provideBleRepository(bluetoothManager: BluetoothManager, context: Context,
                                  authorBleScanner: AuthorBleScanner, authProvider: IAuthProvider): IBluetoothRepository {
    return BluetoothRepository(bluetoothManager, context, authorBleScanner, authProvider)

有关详细信息,您可以阅读此文档:Custom-scopes

或者另一种选择是将 @Singleton 注释添加到您的 BluetoothRepository,然后您只需从参数中获取它,而不是在 privodeBleRepository 上返回一个新对象。