问题
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