Koin injecting into WorkManager

最后都变了- 提交于 2020-06-27 16:39:07

问题


I have a basic work manager

class BackgroundSyncWorker (
    appContext: Context,
    workerParams: WorkerParameters
): Worker(appContext, workerParams) {

    override fun doWork(): Result {
        return Result.success()
    }
}

And I want to inject my repository into this to do some work in my database. I've set Koin up correctly but can't seem to find a way of how to inject my dependency into the Worker. I've tried inheriting the KoinComponent and trying to do it using that, but by inject() doesn't exist, but there's two by inject methods that I can't find how to use. There doesn't seem to be any information on how to inject into managers, although there's a few for using dagger.


回答1:


I have noticed a couple of things from your code:

The first reason for why this does not work because you need to extend/inherit the BackgroundSyncWork from KoinComponent, so making this BackgroundSyncWork koin-aware.

class BackgroundSyncWorker (
    appContext: Context,
    workerParams: WorkerParameters
): Worker(appContext, workerParams), KoinComponent {

val database: Database by inject()

    override fun doWork(): Result {
        return Result.success()
    }
}

Second: Also, please make sure that database object creation is properly configured in koin module. It should work with no problem.




回答2:


This does actually work, I was just using var instead of val.

class BackgroundSyncWorker (
    appContext: Context,
    workerParams: WorkerParameters
): Worker(appContext, workerParams), KoinComponent {

    val dataSyncRepository : DataSyncRepositoryImpl by inject()

    override fun doWork(): Result {
        return Result.success()
    }
}


来源:https://stackoverflow.com/questions/57349196/koin-injecting-into-workmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!