KMP architecture and DI

Learn Kotlin Multiplatform architecture and dependency injection with Koin: shared modules in commonMain, platform modules for Android and iOS, and scopes. About 28 minutes.

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, iOS NSUserDefaults) leak into shared code. An interface in commonMain with platform implementations bound through DI keeps the boundary clean and keeps expect/actual small.
  • 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 single holds 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.

PieceSource setExample
InterfacescommonMainAuthRepository, UserSettings
Shared implementationscommonMainKtorAuthRepository, LoginPresenter
Shared Koin module, initKoin()commonMainsharedModule, expect val platformModule
Android implementationsandroidMainSharedPrefsUserSettings(context)
iOS implementationsiosMainUserDefaultsUserSettings()

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.
  • commonMain gets io.insert-koin:koin-core. koin-android (and koin-androidx-compose) belong in androidMain. With Compose Multiplatform, koin-compose and koin-compose-viewmodel can go in commonMain.
  • single creates one instance for the lifetime of the Koin application, on every platform. factory creates a new instance on every get(). Use single for stateless or app-wide objects (HttpClient, repositories), never for state that belongs to one user or one screen.
  • On Android, Koin's viewModel / viewModelOf definitions tie a ViewModel to a ViewModelStoreOwner. On iOS without Compose Multiplatform, nothing owns the object for you, so use factory or 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 with getKoin().createScope(id, named("session")) and released with scope.close().
  • Call startKoin exactly once. A second call throws KoinApplicationAlreadyStartedException.
  • A missing binding fails only at runtime with NoDefinitionFoundException. Catch it in tests: Koin's verify() 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.kt named initKoinIos() is called as KoinIosKt.doInitKoinIos(), because names starting with "init" get a do prefix.
  • Ktor picks the engine from each source set's dependencies: ktor-client-okhttp in androidMain, ktor-client-darwin in iosMain. Shared code only uses HttpClient.
  • 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") with androidTarget(), iosArm64() and iosSimulatorArm64(); iosX64() is only for Intel Mac simulators and is being phased out. The default hierarchy template creates iosMain.

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 init
  • KtorAuthRepository and LoginPresenter live in commonMain and depend only on interfaces and HttpClient, so there is no if (platform == ...) anywhere.
  • singleOf(::KtorAuthRepository) bind AuthRepository::class resolves 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 expect declaration is platformModule, a property; each platform's actual module binds UserSettings. Android needs androidContext() from koin-android; iOS uses NSUserDefaults from the platform.Foundation bindings.
  • In a real app, keep tokens and secrets out of SharedPreferences and NSUserDefaults; 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

The previous user's data appeared after logout on iOS
  • After logging out and in as a different user, the iOS app briefly showed the previous user's profile and cart.
  • ProfileHolder and CartHolder, which cached per-user state, were registered as single in 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 fix
  • The team moved per-user objects into a Koin session scope: scope(named("session")) { scopedOf(::ProfileHolder); scopedOf(::CartHolder) }.
  • A shared SessionManager creates the scope with getKoin().createScope(userId, named("session")) at login and calls scope.close() at logout, on both platforms.
  • Per-screen presenters became factory definitions, and a test logs in as two users in a row and asserts the second sees only their own data.
iOS crashed at startup with NoDefinitionFoundException
  • A new shared repository needed a SecureStorage interface. The developer added the Android binding and tested on Android only.
  • The iOS app crashed on launch because iosMain's platform module had no SecureStorage binding, and Koin only noticed when the repository was first resolved.
The fix
  • The team added an iosMain implementation backed by the Keychain and bound it in the iOS platform module.
  • They added an iosTest that starts Koin with sharedModule and the iOS platformModule and resolves every top-level type, run in CI with iosSimulatorArm64Test. On Android, Koin's verify() checks the modules' constructor dependencies in a JVM unit test.
  • Where only a factory function differs per platform, they kept a small expect fun instead, so the compiler reports a missing actual before anything runs.

Common mistakes

  • Adding Android-only dependencies to commonMain. koin-android, Hilt and Dagger cannot be resolved for the iOS targets. Put koin-core in commonMain and Android-specific Koin artifacts in androidMain.
  • Using single for per-user or per-screen state. A single lives as long as the Koin application on every platform. Use factory for screen objects and a Koin scope that you close for session state.
  • Using expect/actual classes 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; keep expect for small functions, properties or the platform module.
  • Forgetting the platform module at startup. startKoin { modules(sharedModule) } without the platform module fails with NoDefinitionFoundException when a platform type is first needed. Start Koin from one shared initKoin() that always includes both.
  • Leaking a platform type through a shared interface. An interface in commonMain cannot mention Context or NSUserDefaults at all. Pass shared types and let the platform module construct platform objects.
  • Starting Koin more than once. Calling startKoin again throws KoinApplicationAlreadyStartedException. Start it once at app launch (Android Application, Swift App init) 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)

  1. In a KMP module using kotlin("multiplatform") with androidTarget(), iosArm64() and iosSimulatorArm64(), add io.insert-koin:koin-core to commonMain and io.insert-koin:koin-android to androidMain.
  2. In commonMain, define interface AppClock { fun nowMillis(): Long } and interface Platform { val name: String }.
  3. In androidMain, implement them with System.currentTimeMillis() and "Android". In iosMain, implement them with (NSDate().timeIntervalSince1970 * 1000).toLong() and "iOS". Bind both in an actual val platformModule.
  4. In commonMain, add class GreetingService(private val clock: AppClock, private val platform: Platform) with a greet() that returns the platform name and time. Register it with factoryOf(::GreetingService) in sharedModule, and add initKoin() that starts Koin with sharedModule and platformModule.
  5. Call initKoin { androidContext(this@MyApp) } from Application.onCreate(). In iosMain, add fun initKoinIos() = initKoin() and call KoinIosKt.doInitKoinIos() from the SwiftUI App init.
  6. In commonTest, start Koin with a test module that binds a fixed AppClock and a fake Platform, resolve GreetingService, assert the greeting, and call stopKoin() 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.

Next: Dart for Kotlin developers