I'm using Koin for dependency injection inside a Ktor framework API on Android project using Kotlin. I'm declaring two request scoped instances for being able to have new instances on every new HTTP request. The issue which I'm facing is at time of using the instance. It always throws an exception saying "Request scope is not ready".
The way I'm declaring my modules inside MainActivity.kt:
startKoin {
modules(
module {
single { CancelOrchestration() }
scope<RequestScope> { scopedOf(::PaymentOrchestration) }
scope<RequestScope> { scopedOf(::OfflinePaymentOrchestration) }
}
)
}
And the way I'm trying to use it:
fun Route.paymentsController(){
// Using single instance works fine
val cancelOrchestration by inject<CancelOrchestration>()
post("/payments/{terminalsn?}"){
val requestId = UUID.randomUUID().toString()
//Using request scoped instance throws "Request scope is not ready"
val orchestration = if(TransactionData.isOffline || TransactionData.isOfflineForced) call.scope.get<OfflinePaymentOrchestration>() else call.scope.get<PaymentOrchestration>()
}
}
Anybody with the same issue? Many thanks in advance!
Finally I was able to figured out where the issue came from. My application has a main activity which starts a foreground service where ktor run in a separate thread. I was installing koin modules within the main activity. The non scoped instances were working fine this way but it seems that for request scoped instances you need to install koin in the same thread (if you are using multi-threading) where ktor is running in order to the request scope be ready on ktor routes.