kotlin 如何在HiltWorker中注入依赖项?

sczxawaw  于 2023-03-03  发布在  Kotlin
关注(0)|答案(1)|浏览(150)

I'm trying to inject my repository in a CoroutineWorker annotated like @HiltWorker - after I have followed all the steps in the official docs I'm get this error when trying to inject the repository:
2023-03-02 14:54:08.570 13936-14117 WM-WorkerFactory
it.gabtamagnini.visualstock E Could not instantiate it.gabtamagnini.visualstock.utils.LicenseWorker java.lang.NoSuchMethodException: it.gabtamagnini.visualstock.utils.LicenseWorker. [class android.content.Context, class androidx.work.WorkerParameters] at java.lang.Class.getConstructor0(Class.java:2332) at java.lang.Class.getDeclaredConstructor(Class.java:2170) at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:95) at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:243) at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:145) at androidx.work.impl.utils.SerialExecutorImpl$Task.run(SerialExecutorImpl.java:96) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:919) 2023-03-02 14:54:08.571 13936-14117 WM-WorkerWrapper it.gabtamagnini.visualstock
E Could not create Worker it.gabtamagnini.visualstock.utils.LicenseWorker
The Worker looks like this:

@HiltWorker
class LicenseWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted params: WorkerParameters,
    private val repository: LicenseRepository
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        // TODO: check if the license if still valid and if so return Result.success() else Result.failure()
        return try {
            val license = withContext(Dispatchers.IO) {
                repository.getLicense()
            }
            Log.i("License", license.id)
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        }
    }

}

Manifest:

<provider
        android:name="androidx.startup.InitializationProvider"
        android:authorities="${applicationId}.androidx-startup"
        tools:node="remove">
    </provider>

Application:

@HiltAndroidApp
class BaseApplication : Application(), Configuration.Provider {
    @Inject
    lateinit var workerFactory: HiltWorkerFactory

    override fun getWorkManagerConfiguration() = Configuration.Builder()
        .setWorkerFactory(workerFactory)
        .build()
}

That happens not only with that repository but with any dependency I try to inject.
If I remove all the dependencies and return only a Result.success() it will work without any problems.

epfja78i

epfja78i1#

这是一个依赖性问题,因为我只有:在我的build.gradle里。
为了解决这个问题,我甚至不得不添加kapt("androidx.hilt:hilt-compiler:1.0.0")
根据文件

相关问题