InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.76k stars 695 forks source link

Scope instances not getting cleanedup properly #1896

Open lexa-diky opened 1 week ago

lexa-diky commented 1 week ago

Describe the bug Very similar to: https://github.com/InsertKoinIO/koin/issues/1176 Scopes created by KoinScopeComponent are sharing instance cache.

Good real-life example is RequestScope form koin-ktor. If somewhere mid pipeline we fail to register one of instances via scope.declare and fail, instance from previously successful requests will still be returned by Koin when requested further down the pipeline.

To Reproduce Isolated case:

class MyScopeComponent(private val _koin: Koin) : KoinScopeComponent {
    override fun getKoin(): Koin = _koin
    override val scope: Scope = createScope()
}

fun main() {
    val koin = koinApplication { printLogger(Level.DEBUG) }.koin

    val scopeComponent = MyScopeComponent(koin)
    val scope = scopeComponent.scope
    scope.declare("hello")
    require("hello" == scope.get<String>())

    scope.close()

    val scopeComponent2 = MyScopeComponent(koin)
    val scope2 = scopeComponent2.scope

    require(scope2.getOrNull<String>() == null)
}

Expected behavior Both require expressions in "To reproduce" should pass

Koin module and version: koin-core:3.5.5

Snippet or Sample project to help reproduce See "To reproduce"