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

时间:2019-06-27 10:50:42

标签: android dependency-injection dagger-2

我在带有@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内部使用了变量,将其初始化并从provideBleRepository()返回,但我认为必须有更简单的方法

1 个答案:

答案 0 :(得分:0)

您可以使用@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上返回新对象。