InsertKoinIO / koin

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

[core] Ensure onClose callbacks are invoked in reversed initialization order #2020

Open shchuko opened 1 month ago

shchuko commented 1 month ago

Fixes #1510

onClose callback can be used to release allocated resources like DB connections. Discussion #1507

Some beans can depend on each other.

An example: classic Web application consists of Controller, Service, Database.

In this case, instantiation order is:   1. Database   2. Service - implements business logic, requires Database   3. Controller - REST controller, requires Service

On application graceful shutdown, onClose invocation order must be reversed:   1. Controller - created last, destroyed first   2. Service - destroyed after Controller to avoid use-after-close   3. Database - destroyed after Service to avoid use-after-close

This commit delivers implementation of onClose calls ordering.

When instance factory creates its first instance, it means that all dependencies are also created. So it's enough to sort factories by 'first instance creation,' and then reverse the sequence when invoking onClose.

Implementation: