MyRepository
class MyRepository @Inject constructor(
private val myDao: IMyDao
){
...
}
MyModule
@InstallIn(SingletonComponent::class)
@Module
class MyModule {
@Provides
fun provideMyRepository(MyDao: IMyDao): MyRepository{
return MyRepository(MyDao)
}
}
Use in Worker
class MyWorker(appContext: Context, workerParams: WorkerParameters) :
Worker(appContext, workerParams) {
private val myRepository: MyRepository =
EntryPointAccessors.fromApplication(appContext, MyRepository::class.java)
}
start worker in Application class.
but got error: java.lang.ClassCastException: Cannot cast com.freedom.android.DaggerMyApplication_HiltComponents_SingletonC$SingletonCImpl to com.freedom.android.MyRepository
I read the relevant documentation.But I don't want to use the interface, I just want the class to be provided.
Please tell me what is the problem.
CodePudding user response:
In this case you need to use hilt worker
@HiltWorker class WokerName @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted params: WorkerParameters,
myRepository: MyRepository): CoroutineWorker(appContext, params)
Go through all the links below you will get all the gradel dependency, how to use them etc..
https://developer.android.com/training/dependency-injection/hilt-jetpack#kotlin https://developer.android.com/reference/androidx/hilt/work/HiltWorker https://developer.android.com/guide/background/persistent/configuration/custom-configuration https://developer.android.com/topic/libraries/app-startup