InsertKoinIO / koin-annotations

Koin Annotations - About Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform insert-koin.io
https://insert-koin.io
Apache License 2.0
123 stars 30 forks source link

Provide constructor or method injection for anroid context for koin annotations #126

Open steve1rm opened 2 months ago

steve1rm commented 2 months ago

How to provide a context to and class constructor in koin annotations

I have the following class that needs an context for the sharedPreferences. However, when using koin annotations I am not sure how to provide this context.

e: [ksp] --> Missing Definition type 'android.content.Context' for 'me.androidbox.data.local.imp.UserTokenLocalDataSourceImp'. Fix your configuration to define type 'Context'.
e: Error occurred in KSP, check log for detail
@Single
class UserTokenLocalDataSourceImp(context: Context) : UserTokenLocalDataSource {

    companion object {
        private const val TOKEN = "token"
        private const val FILE_NAME = "secret_shared_prefs"
    }

    private val masterKeys = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
    private val encryptedSharedPreferences =
        EncryptedSharedPreferences.create(
            FILE_NAME,
            masterKeys,
            context,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )

    override suspend fun saveUserToken(token: String) {
        encryptedSharedPreferences.edit {
            this.putString(TOKEN, token)
            this.apply()
        }
    }

    override suspend fun fetchUserToken(): String? {
        return encryptedSharedPreferences.getString(TOKEN, null)
    }
}

In my module I have the following:

@Module
@ComponentScan
class UserTokenLocalDataSourceModule {

  fun provideUserTokenLocalDataSourceImp(): UserTokenLocalDataSource {
        return UserTokenLocalDataSourceImp(androidContext())
    }
}

I thought I could use the androidContext() the same way we use the koin DSL, but I get the following androidContext() unresolved reference

In my application class I have the following:

 startKoin {
            androidLogger()
            androidContext(this@BusbyTravelMateApplication)
            modules(
                UserTokenLocalDataSourceModule().module,
            )
        }

The versions I am using:

kspVersion = "1.9.23-1.0.20"
koinVersion = "3.5.3"
kspKoinVersion = "1.3.0"
Jadarma commented 2 months ago

This problem is similar to what I described in #95. Unfortunately the checks don't play nice when combining annotated modules and manual DSL. Since you register the Android context in the DSL at runtime, a compile time check cannot verify it.