Search code examples
androidkotlinkoin

Android Koin simple object inject fail


I'm trying to learn Koin for dependency injection in android. I started to follow the example and try to inject very simple object by but I'm getting the error as NoBeanDefFoundException: No definition found for ...

here's my code

Gradle

// Koin
    def koin_version = '2.0.1'
    implementation "org.koin:koin-androidx-scope:$koin_version"
    implementation "org.koin:koin-androidx-viewmodel:$koin_version"
    implementation "org.koin:koin-androidx-ext:$koin_version" 

Application onCreate()

override fun onCreate() {
        super.onCreate()

        startKoin{
            androidLogger()
            androidContext(this@Application)
            listOf(applicationModule)
        }

    }

Modules.kt

val applicationModule = module {
    factory { UserSession("email","password") }
}

but when I try to inject it in anywhere (Application, Activity, Fragment) as private val userSession: UserSession by inject() I get above mentioned error. Am I missing something?


Solution

  • You probably got confused by the syntax, you're supposed to call the method modules and provide it with the modules you want started.

    The listOf return value is ignored in your case, you're supposed to do something like this:

    startKoin {
        androidLogger()
        androidContext(this@Application)
        modules(applicationModule)
    }
    

    Reference