我正在使用 Kotlin 在 Android 项目上的 Ktor 框架 API 中使用 Koin 进行依赖项注入。我声明了两个请求范围的实例,以便能够在每个新的 HTTP 请求上拥有新的实例。我面临的问题是在使用实例时。它总是抛出一个异常,说“请求范围尚未准备好”。
我在 MainActivity.kt 中声明模块的方式:
startKoin {
modules(
module {
single { CancelOrchestration() }
scope<RequestScope> { scopedOf(::PaymentOrchestration) }
scope<RequestScope> { scopedOf(::OfflinePaymentOrchestration) }
}
)
}
以及我尝试使用它的方式:
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>()
}
}
有人有同样的问题吗? 非常感谢!
终于知道问题出在哪里了。 我的应用程序有一个主要活动,它启动一个前台服务,其中 ktor 在单独的线程中运行。我正在主要活动中安装 koin 模块。非作用域实例以这种方式工作正常,但似乎对于请求作用域实例,您需要在 ktor 运行的同一线程(如果您使用多线程)中安装 koin,以便请求作用域在 ktor 路由上做好准备.