KMP architecture and DI
Why it matters
- Hilt and Dagger are JVM/Android-only, so a Kotlin Multiplatform (KMP) project that shares business logic needs a DI approach that works in
commonMain. Koin is the most common choice; kotlin-inject and manual constructor injection also work. Knowing Koin's module DSL and lifetimes is a regular KMP interview topic. - The most common KMP architecture mistake is letting a platform type (Android
Context, iOSNSUserDefaults) leak into shared code. An interface incommonMainwith platform implementations bound through DI keeps the boundary clean and keepsexpect/actualsmall. - Interviewers ask you to draw the source-set graph, say where the Koin modules live, how iOS starts the graph, and what happens when a
singleholds per-user state after logout. - Getting the architecture wrong means either duplicating logic per platform (losing the point of KMP) or discovering a missing binding only when the iOS app crashes at startup.
The simple explanation
How do you do dependency injection in Kotlin Multiplatform? Put interfaces, repositories, use cases and a shared Koin module in commonMain. Each platform source set (androidMain, iosMain) implements the platform-specific interfaces and provides a platform Koin module. A shared initKoin() function starts Koin once with both modules; Android calls it from Application.onCreate() and iOS calls it from Swift at app start.
- One recipe book (
commonMain) is shared by every kitchen. - Each kitchen (
androidMain,iosMain) has its own stove. - The recipe says "heat to 180 degrees", never "use a gas burner".
- The head chef (Koin) hands each kitchen the right tool when the recipe needs it.
Interfaces plus DI, with small expect/actual. expect/actual is resolved at compile time: every target must provide an actual. Functions and properties are stable, but expect/actual classes are still Beta. For behaviour that differs per platform, define an interface in commonMain and bind a platform implementation in DI; tests can then swap in a fake. Koin's own KMP setup uses one small expect val platformModule: Module, with an actual module per platform.
Koin in KMP. Add io.insert-koin:koin-core to commonMain (usually through koin-bom or a version catalog). Add koin-android only to androidMain for androidContext(). There is no separate iOS artifact; koin-core already supports the iOS targets.
| Piece | Source set | Example |
|---|---|---|
| Interfaces | commonMain | AuthRepository, UserSettings |
| Shared implementations | commonMain | KtorAuthRepository, LoginPresenter |
Shared Koin module, initKoin() | commonMain | sharedModule, expect val platformModule |
| Android implementations | androidMain | SharedPrefsUserSettings(context) |
| iOS implementations | iosMain | UserDefaultsUserSettings() |
Only the platform modules know about Context or NSUserDefaults. Prefer constructor injection everywhere; call get() only inside module definitions, and use KoinComponent / inject() only at the edges (for example a Swift-facing helper).
Notes
- Hilt and Dagger are JVM/Android-only and cannot be used in
commonMain. Koin and kotlin-inject work in common code; manual constructor injection always works. commonMaingetsio.insert-koin:koin-core.koin-android(andkoin-androidx-compose) belong inandroidMain. With Compose Multiplatform,koin-composeandkoin-compose-viewmodelcan go incommonMain.singlecreates one instance for the lifetime of the Koin application, on every platform.factorycreates a new instance on everyget(). Usesinglefor stateless or app-wide objects (HttpClient, repositories), never for state that belongs to one user or one screen.- On Android, Koin's
viewModel/viewModelOfdefinitions tie a ViewModel to aViewModelStoreOwner. On iOS without Compose Multiplatform, nothing owns the object for you, so usefactoryor a Koin scope that you close yourself. - Koin scopes group objects that live together, such as a logged-in session:
scope(named("session")) { scoped { ... } }, created withgetKoin().createScope(id, named("session"))and released withscope.close(). - Call
startKoinexactly once. A second call throwsKoinApplicationAlreadyStartedException. - A missing binding fails only at runtime with
NoDefinitionFoundException. Catch it in tests: Koin'sverify()on the JVM, plus a test that starts the real graph and resolves key types on each platform. - From Swift, a top-level Kotlin function in
KoinIos.ktnamedinitKoinIos()is called asKoinIosKt.doInitKoinIos(), because names starting with "init" get adoprefix. - Ktor picks the engine from each source set's dependencies:
ktor-client-okhttpinandroidMain,ktor-client-darwininiosMain. Shared code only usesHttpClient. - Room (KMP support since 2.7) and SQLDelight both work for a shared database. Either way, the repository is built in shared code and only the driver or builder is platform-specific.
- The Gradle plugin is
kotlin("multiplatform")withandroidTarget(),iosArm64()andiosSimulatorArm64();iosX64()is only for Intel Mac simulators and is being phased out. The default hierarchy template createsiosMain.
Code example
A shared module in commonMain, one platform module per target, and a single initKoin() entry point. LoginPresenter and KtorAuthRepository are shared; only UserSettings has platform implementations.
// ---- commonMain: di/SharedModule.kt ----
import io.ktor.client.HttpClient
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.Serializable
import org.koin.core.context.startKoin
import org.koin.core.module.Module
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.KoinAppDeclaration
import org.koin.dsl.bind
import org.koin.dsl.module
interface UserSettings {
var lastEmail: String?
}
interface AuthRepository {
suspend fun login(email: String, password: String)
}
@Serializable
data class LoginRequest(val email: String, val password: String)
class KtorAuthRepository(
private val http: HttpClient,
private val settings: UserSettings,
) : AuthRepository {
override suspend fun login(email: String, password: String) {
http.post("https://api.example.com/login") {
contentType(ContentType.Application.Json)
setBody(LoginRequest(email, password))
}
settings.lastEmail = email
}
}
class LoginPresenter(private val repo: AuthRepository) {
suspend fun submit(email: String, password: String) = repo.login(email, password)
}
expect val platformModule: Module
val sharedModule = module {
// Engine comes from the platform dependency: OkHttp on Android, Darwin on iOS
single { HttpClient { install(ContentNegotiation) { json() } } }
singleOf(::KtorAuthRepository) bind AuthRepository::class
factoryOf(::LoginPresenter)
}
fun initKoin(config: KoinAppDeclaration? = null) {
startKoin {
config?.invoke(this)
modules(sharedModule, platformModule)
}
}
// ---- androidMain: di/PlatformModule.android.kt ----
import android.content.Context
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
class SharedPrefsUserSettings(context: Context) : UserSettings {
private val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
override var lastEmail: String?
get() = prefs.getString("last_email", null)
set(value) { prefs.edit().putString("last_email", value).apply() }
}
actual val platformModule = module {
single<UserSettings> { SharedPrefsUserSettings(androidContext()) }
}
// In Application.onCreate(): initKoin { androidContext(this@MyApp) }
// ---- iosMain: di/PlatformModule.ios.kt and KoinIos.kt ----
import org.koin.dsl.module
import platform.Foundation.NSUserDefaults
class UserDefaultsUserSettings : UserSettings {
private val defaults = NSUserDefaults.standardUserDefaults
override var lastEmail: String?
get() = defaults.stringForKey("last_email")
set(value) { defaults.setObject(value, forKey = "last_email") }
}
actual val platformModule = module {
single<UserSettings> { UserDefaultsUserSettings() }
}
fun initKoinIos() = initKoin() // Swift: KoinIosKt.doInitKoinIos() in the App initKtorAuthRepositoryandLoginPresenterlive incommonMainand depend only on interfaces andHttpClient, so there is noif (platform == ...)anywhere.singleOf(::KtorAuthRepository) bind AuthRepository::classresolves the constructor parameters from the graph and registers the instance under the interface type.factoryOf(::LoginPresenter)gives every screen its own presenter, so no screen inherits another's state.- The only
expectdeclaration isplatformModule, a property; each platform'sactualmodule bindsUserSettings. Android needsandroidContext()fromkoin-android; iOS usesNSUserDefaultsfrom theplatform.Foundationbindings. - In a real app, keep tokens and secrets out of
SharedPreferencesandNSUserDefaults; use encrypted storage on Android and the Keychain on iOS.
Run the idea in plain Kotlin
A tiny container with single and factory shows how merging the shared module with a platform module changes the binding, and what happens when the platform module is forgotten.
import kotlin.reflect.KClass
class Definition(val single: Boolean, val create: (Container) -> Any)
class Module(val defs: Map<KClass<*>, Definition>)
class ModuleBuilder {
val defs = mutableMapOf<KClass<*>, Definition>()
inline fun <reified T : Any> single(noinline create: (Container) -> T) {
defs[T::class] = Definition(true, create)
}
inline fun <reified T : Any> factory(noinline create: (Container) -> T) {
defs[T::class] = Definition(false, create)
}
}
fun module(block: ModuleBuilder.() -> Unit) = Module(ModuleBuilder().apply(block).defs)
class Container(modules: List<Module>) {
private val defs = modules.flatMap { it.defs.entries }.associate { it.key to it.value }
private val singles = mutableMapOf<KClass<*>, Any>()
inline fun <reified T : Any> get(): T = resolve(T::class) as T
fun resolve(type: KClass<*>): Any {
val def = defs[type] ?: throw IllegalStateException("No definition for " + type.simpleName)
return if (def.single) singles.getOrPut(type) { def.create(this) } else def.create(this)
}
}
interface UserSettings { val platform: String }
class SharedPrefsUserSettings : UserSettings { override val platform = "Android" }
class UserDefaultsUserSettings : UserSettings { override val platform = "iOS" }
class AuthRepository(val settings: UserSettings)
class LoginPresenter(val repo: AuthRepository)
val sharedModule = module {
single { AuthRepository(it.get()) }
factory { LoginPresenter(it.get()) }
}
val androidModule = module { single<UserSettings> { SharedPrefsUserSettings() } }
val iosModule = module { single<UserSettings> { UserDefaultsUserSettings() } }
fun main() {
for (platformModule in listOf(androidModule, iosModule)) {
val koin = Container(listOf(sharedModule, platformModule))
val first = koin.get<LoginPresenter>()
val second = koin.get<LoginPresenter>()
println("Settings: " + first.repo.settings.platform)
println(" same repository (single): " + (first.repo === second.repo))
println(" same presenter (factory): " + (first === second))
}
val broken = Container(listOf(sharedModule))
try {
broken.get<LoginPresenter>()
} catch (e: IllegalStateException) {
println("Forgot the platform module: " + e.message)
}
}Expected output:
Settings: Android
same repository (single): true
same presenter (factory): false
Settings: iOS
same repository (single): true
same presenter (factory): false
Forgot the platform module: No definition for UserSettings
In production
- After logging out and in as a different user, the iOS app briefly showed the previous user's profile and cart.
ProfileHolderandCartHolder, which cached per-user state, were registered assinglein the shared module, so they lived as long as the Koin application.- On Android the same classes had been wrapped in ViewModels, which hid the problem; the iOS screens resolved them directly from Koin.
- The team moved per-user objects into a Koin session scope:
scope(named("session")) { scopedOf(::ProfileHolder); scopedOf(::CartHolder) }. - A shared
SessionManagercreates the scope withgetKoin().createScope(userId, named("session"))at login and callsscope.close()at logout, on both platforms. - Per-screen presenters became
factorydefinitions, and a test logs in as two users in a row and asserts the second sees only their own data.
- A new shared repository needed a
SecureStorageinterface. The developer added the Android binding and tested on Android only. - The iOS app crashed on launch because
iosMain's platform module had noSecureStoragebinding, and Koin only noticed when the repository was first resolved.
- The team added an
iosMainimplementation backed by the Keychain and bound it in the iOS platform module. - They added an
iosTestthat starts Koin withsharedModuleand the iOSplatformModuleand resolves every top-level type, run in CI withiosSimulatorArm64Test. On Android, Koin'sverify()checks the modules' constructor dependencies in a JVM unit test. - Where only a factory function differs per platform, they kept a small
expect funinstead, so the compiler reports a missingactualbefore anything runs.
Common mistakes
- Adding Android-only dependencies to commonMain.
koin-android, Hilt and Dagger cannot be resolved for the iOS targets. Putkoin-coreincommonMainand Android-specific Koin artifacts inandroidMain. - Using
singlefor per-user or per-screen state. Asinglelives as long as the Koin application on every platform. Usefactoryfor screen objects and a Koin scope that you close for session state. - Using
expect/actualclasses for every platform difference. They are still Beta, harder to fake in tests and force every target to implement the whole class. Prefer an interface bound in DI; keepexpectfor small functions, properties or the platform module. - Forgetting the platform module at startup.
startKoin { modules(sharedModule) }without the platform module fails withNoDefinitionFoundExceptionwhen a platform type is first needed. Start Koin from one sharedinitKoin()that always includes both. - Leaking a platform type through a shared interface. An interface in
commonMaincannot mentionContextorNSUserDefaultsat all. Pass shared types and let the platform module construct platform objects. - Starting Koin more than once. Calling
startKoinagain throwsKoinApplicationAlreadyStartedException. Start it once at app launch (AndroidApplication, SwiftAppinit) and use scopes for shorter lifetimes.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you structure a KMP project so business logic is shared but platform code stays isolated?”
“Why can you not use Hilt in KMP shared code, and what do you use instead?”
“What is the difference between single and factory in Koin, and when does it matter in KMP?”
“When would you still use expect/actual instead of an interface plus DI?”
Quiz
Which DI library can be used in commonMain of a KMP project?
A class holding the current user's profile is registered as single in Koin. What happens after logout and login as another user, if nothing else is done?
Where does the Ktor OkHttp engine dependency belong in a KMP project?
What is the usual recommendation for platform-specific behaviour in KMP shared code?
0 of 4 answered
Mini task
Wire a shared and platform Koin graph (20 min)
- In a KMP module using
kotlin("multiplatform")withandroidTarget(),iosArm64()andiosSimulatorArm64(), addio.insert-koin:koin-coretocommonMainandio.insert-koin:koin-androidtoandroidMain. - In
commonMain, defineinterface AppClock { fun nowMillis(): Long }andinterface Platform { val name: String }. - In
androidMain, implement them withSystem.currentTimeMillis()and"Android". IniosMain, implement them with(NSDate().timeIntervalSince1970 * 1000).toLong()and"iOS". Bind both in anactual val platformModule. - In
commonMain, addclass GreetingService(private val clock: AppClock, private val platform: Platform)with agreet()that returns the platform name and time. Register it withfactoryOf(::GreetingService)insharedModule, and addinitKoin()that starts Koin withsharedModuleandplatformModule. - Call
initKoin { androidContext(this@MyApp) }fromApplication.onCreate(). IniosMain, addfun initKoinIos() = initKoin()and callKoinIosKt.doInitKoinIos()from the SwiftUIAppinit. - In
commonTest, start Koin with a test module that binds a fixedAppClockand a fakePlatform, resolveGreetingService, assert the greeting, and callstopKoin()afterwards.
Done condition: both apps show a greeting with the correct platform name, and the commonTest test passes on the JVM and with ./gradlew iosSimulatorArm64Test without changing GreetingService.