koin-annotations icon indicating copy to clipboard operation
koin-annotations copied to clipboard

Provide constructor or method injection for anroid context for koin annotations

Open steve1rm opened this issue 10 months ago • 1 comments

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"

steve1rm avatar Apr 13 '24 05:04 steve1rm

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.

Jadarma avatar Apr 17 '24 11:04 Jadarma

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 15 '24 00:09 stale[bot]