InsertKoinIO / koin

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

KoinComponent with KoinApplication composable not working #1719

Closed farhazulmullick-pw closed 8 months ago

farhazulmullick-pw commented 10 months ago

If i call this KoinApplicationComposable from MainActivity then if i try to inject any dependency using by inject() in any class with KoinComponent interface implemented. I get a runtime exception java.lang.IllegalStateException: KoinApplication has not been started.

Further this runtime exception is not thrown if startKoin {} is called in Application class.


@Composable
fun KoinApplicationComposable(
    application: Application,
    appContent: @Composable () -> Unit
) {
   org.koin.compose.KoinApplication(application = {
        androidContext(application.applicationContext)
        modules(getKoinModules())
    }){
        appContent()
        Test.testInstace    // throws java.lang.IllegalStateException KoinApplication has not been started.
    }
}

fun getKoinModules() = module {
      single<SomeClass> { ... }
}

public object Test: KoinComponent {
    val instance by inject<SomeClass>()

    fun testInstance() = instance

}
shohrab-swl commented 9 months ago

Same problem, can anyone fix it?

arnaudgiuliani commented 8 months ago

your Koin instance is not yet start while you use Test, which is extending KoinComponent. Either you delay it elsewhere, after the KoinApplication block. Either you can start Koin with startKoin before using KoinApplication