kosi-libs / Kodein

Painless Kotlin Dependency Injection
https://kosi-libs.org/kodein
MIT License
3.19k stars 174 forks source link

How to provide disable Kodein shared preferences module #451

Closed daniel-waiguru closed 5 months ago

daniel-waiguru commented 7 months ago

I am working on a project with the android module enabled import(androidXModule(this)) but I need to provide a new secure SharedPreferences implementation without removing import(androidXModule(this)) how do I disable the sharedpreference only from the androidx module?

romainbsl commented 5 months ago

You cannot disable part of a module. However, you can override it.

daniel-waiguru commented 5 months ago

Overriding it throws an exception. Caused by: org.kodein.di.Kodein$OverridingException: Binding bind<SharedPreferences>() with ? { ? } must override an existing binding. at org.kodein.di.internal.KodeinContainerBuilderImpl.checkOverrides(KodeinContainerBuilderImpl.kt:106) at org.kodein.di.internal.KodeinContainerBuilderImpl.bind(KodeinContainerBuilderImpl.kt:115) at org.kodein.di.internal.KodeinBuilderImpl$TypeBinder.with(KodeinBuilderImpl.kt:20)

Or am I missing something?

romainbsl commented 5 months ago

Yeah, SharedPrefences is scoped on the Android Context, see the definition here:

https://github.com/kosi-libs/Kodein/blob/c9d169d73fe4e99c43febcdcead92e9d3ff8c7d3/framework/android/kodein-di-framework-android-core/src/main/java/org/kodein/di/android/module.kt#L104

You probably need to do something like:

val contextToken = generic<Context>()
bind(overrides = true) { Provider(contextToken, generic()) { /* Your implementation */ } }

Or:

bind(overrides = true) { contexted<Context>().provider { /* Your implementation */ } }