【问题标题】:Couldn't inject @Binds Hilt Dependencies in WorkManager using @WorkerInject无法使用 @WorkerInject 在 WorkManager 中注入 @Binds Hilt 依赖项
【发布时间】:2021-01-12 10:47:45
【问题描述】:

我尝试使用以下代码构建

Followed the Hilt-WorkManager official documentation

工人阶级

class StartJobWorker @WorkerInject constructor(
    @Assisted appContext: Context,
    @Assisted workerParams: WorkerParameters,
    private val startJobUseCase: StartJobUseCase,
) : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork(): Result {
        val jobId: Long = inputData.getLong(AppConstant.JOB_ID, 0)
        return when (val workResult: WorkResult = startJobUseCase(jobId)) {
            is WorkResult.Success<*> -> Result.success()
            is WorkResult.Failure<*> -> Result.failure()
            WorkResult.Retry -> Result.retry()
        }
    }

}

刀柄模块

@Module
@InstallIn(ActivityComponent::class)
abstract class UseCaseModule {

    @ActivityScoped
    @Binds
    abstract fun bindStartJobUseCase(startJobUseCaseImpl: StartJobUseCaseImpl): StartJobUseCase

}

依赖抽象

interface StartJobUseCase {
    suspend operator fun invoke(jobId: Long): WorkResult
}

依赖实现

class StartJobUseCaseImpl @Inject constructor(
    private val startJobRepository: StartJobRepository
) : StartJobUseCase {

    override suspend fun invoke(jobId: Long): WorkResult {
        return startJobRepository.startJob(jobId)
    }

}

我在编译时收到以下错误消息。

error: [Dagger/MissingBinding] com.example.domain.StartJobUseCase cannot be provided without an @Provides-annotated method.

请告诉我此问题的解决方案。

【问题讨论】:

    标签: android android-workmanager dagger-hilt


    【解决方案1】:

    正如 EpicPandaForce 所说,将 ActivityComponent 与 ApplicationComponent 交换并在 UseCaseModule 类中删除 @ActivityScoped 解决了这个问题。

    刀柄模块

    @Module
    @InstallIn(ActivityComponent::class)
    abstract class UseCaseModule {
    
        @Binds
        abstract fun bindStartJobUseCase(startJobUseCaseImpl: StartJobUseCaseImpl): StartJobUseCase
    
    }
    

    【讨论】:

    • 解决方案是将ActivityComponent 换成ApplicationComponentprovides vs binds 与解决方案无关。
    • 你是对的,我的错。用 ApplicationComponent 交换 ActivityComponent 解决了这个问题
    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2020-12-07
    • 2021-05-31
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多