InsertKoinIO / koin

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

Ktor Install(Koin) doesn't trigger createEagerInstances #547

Closed antohaby closed 4 years ago

antohaby commented 5 years ago

Describe the bug When using koin as Ktor feature beans that defined with "createAtStart=true" attribute doesn't actually start.

To Reproduce

  1. Create simple ktor application
  2. Install Koin with any bean with createdAtStart=true and call println for example inside the body.
  3. Start the application
  4. Nothing happened
  5. Get bean explicitly, a message is printed.

Expected behavior Bean has to be created at the start of Ktor application

Koin project used and used version (please complete the following information): koin-core version 2.0.1 koin-ktor version 2.0.1

Cause Installation function (https://github.com/InsertKoinIO/koin/blob/7cd226d85b6d4efce90d16f8bd717792cdae87db/koin-projects/koin-ktor/src/main/kotlin/org/koin/ktor/ext/KoinFeature.kt#L37) doesn't trigger createEagerInstances

As for example GlobalContext.startKoin (https://github.com/InsertKoinIO/koin/blob/master/koin-projects/koin-core/src/main/kotlin/org/koin/core/context/GlobalContext.kt#L69) does

Workaround Call createEagerInstances() during installation

    install(Koin) {
        /*...*/
        modules(/*...*/)
        // Call after modules are set
        createEagerInstances()
    }

Possible fix In Koin.install instead GlobalContext.start(application) use GlobalContext.startKoin(configure)

class Koin {
/* ... */
        override fun install(pipeline: Application, configure: KoinAppDeclaration): Koin {
            startKoin(configure)
            pipeline.environment.monitor.subscribe(ApplicationStopping) {
                GlobalContext.stop()
            }
            return Koin()
        }
    }
}
BorzdeG commented 4 years ago

This bug is fixed at https://github.com/InsertKoinIO/koin/pull/548

arnaudgiuliani commented 4 years ago

Let's continue there #548 then 👍