Koin 获取请求范围实例时出错:请求范围尚未准备好

问题描述 投票:0回答:1

我正在使用 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>()
     }
 }

有人有同样的问题吗? 非常感谢!

android ktor koin koin-scope
1个回答
0
投票

终于知道问题出在哪里了。 我的应用程序有一个主要活动,它启动一个前台服务,其中 ktor 在单独的线程中运行。我正在主要活动中安装 koin 模块。非作用域实例以这种方式工作正常,但似乎对于请求作用域实例,您需要在 ktor 运行的同一线程(如果您使用多线程)中安装 koin,以便请求作用域在 ktor 路由上做好准备.

© www.soinside.com 2019 - 2024. All rights reserved.