Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

android - Couldn't inject @Binds Hilt Dependencies in WorkManager using @WorkerInject

I tried to build with the following code in

Followed the Hilt-WorkManager official documentation

Worker class

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()
        }
    }

}

Hilt Module

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

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

}

Dependency abstraction

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

Dependency Implementation

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

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

}

I got the following error message in the compilation.

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

Please let me know the solution for this issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As EpicPandaForce said, Swapping ActivityComponent with ApplicationComponent and removing @ActivityScoped in UseCaseModule class fixed the issue.

Hilt Module

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

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...