agentleFS
KushpawanKushpawan/kmp-mobile-skills/skills/kmp-koin-di/SKILL.md

kmp-koin-di

Skill15 starsChanged 25 days agoApache-2.0View on GitHub

Use when setting up, extending or debugging Koin dependency injection in a Kotlin Multiplatform app — modules in commonMain, platform modules, startKoin in Application, initKoin called from Swift, koinViewModel in Compose Multiplatform, qualifiers, scopes, test overrides — or on NoDefinitionFoundException, InstanceCreationException, KoinApplicationAlreadyStartedException, "KoinApplication has not been started", or a launch crash only on iOS.

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Never call get() at module level or inside a callback that runs later — only inside a definition lambda, where it resolves when the …

    line 106
  2. Very specific:

    Start Koin before the first Compose MainViewController() or any Swift call into Koin-backed code.

    line 191
  3. Very specific:

    Keep the facade narrow — one per feature, returning interfaces.

    line 229

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Koin in Kotlin Multiplatform

Declare dependencies once in commonMain, add a small platform module for what only Android or iOS can build, start Koin exactly once per process on each platform — in a fixed order — and prove the graph resolves with a test instead of with a launch crash.

When to use

  • Adding Koin to a KMP project, or adding modules, ViewModels or platform bindings to an existing graph.
  • Starting Koin from Swift, or getting a shared dependency into SwiftUI code.
  • Errors: NoDefinitionFoundException: No definition found for type ..., InstanceCreationException: Could not create instance for ..., KoinApplicationAlreadyStartedException: A Koin Application has already been started, IllegalStateException: KoinApplication has not been started.
  • Tests that leak Koin state between cases or fail only when run together.

When not to use

  • The project uses Hilt (Android-only), kotlin-inject, Kodein or manual constructor wiring — keep that framework; do not add Koin beside it. The ordering and verification ideas here still apply.
  • Deciding what the dependencies are (client, repositories) — kmp-data-layer.
  • expect/actual design beyond DI bindings — kmp-expect-actual.

Step 0 — Read the project first

grep -nE "koin|hilt|kotlin-inject|kodein" gradle/libs.versions.toml
grep -rnE "startKoin|initKoin|koinApplication|KoinApplication\(" --include=*.kt --include=*.swift .
grep -rnE "^val [a-zA-Z]+Module = module|includes\(" --include=*.kt . | head -30
grep -rnE "@Module|@Single|@Factory|@KoinViewModel" --include=*.kt . | head    # Koin Annotations?
grep -rnE "named\(|qualifier" --include=*.kt . | head
FindingThen
Koin DSL modules (module { })Follow their layout and naming; add to the existing aggregator.
Koin Annotations (@Module, @Single)Write annotated classes, not DSL — mixing styles confuses readers.
Existing initKoinExtend it; never add a second startKoin.
Existing qualifiersReuse the exact names. A typo in named("authenticated") is a runtime failure.
Koin versionKoin 4.x APIs below. ViewModel DSL lives in org.koin.core.module.dsl; the old org.koin.compose.viewmodel.dsl imports are deprecated.

Workflow

1. Dependencies

# gradle/libs.versions.toml — keep the Koin version the catalog pins (or use its BOM)
[libraries]
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
koin-android = { module = "io.insert-koin:koin-android", version.ref = "koin" }
koin-compose = { module = "io.insert-koin:koin-compose", version.ref = "koin" }
koin-compose-viewmodel = { module = "io.insert-koin:koin-compose-viewmodel", version.ref = "koin" }
koin-test = { module = "io.insert-koin:koin-test", version.ref = "koin" }
Source setAdd
commonMainkoin-core; koin-compose + koin-compose-viewmodel only in modules with Compose UI
androidMainkoin-android
commonTestkoin-test

A module that exports a framework consumed by SwiftUI (no Compose) needs only koin-core.

2. Lay out modules by layer, aggregate once

// commonMain — profile/di/ProfileModule.kt
val profileModule = module {
    single<ProfileApi> { KtorProfileApi(client = get(named("authenticated"))) }
    singleOf(::ProfileRepositoryImpl) bind ProfileRepository::class
    factoryOf(::GetProfileUseCase)
    viewModelOf(::ProfileViewModel)
}

// commonMain — di/AppModules.kt
fun appModules(): List<Module> = listOf(
    coreModule,          // logger bridge, dispatchers, Json
    networkModule,       // HttpClient instances, token refresher
    databaseModule,      // database and DAOs
    platformModule,      // expect/actual, step 3
    profileModule,       // features last
)
DefinitionUse for
single / singleOfStateful or expensive: HttpClient, database, repositories, session holders
factory / factoryOfStateless and cheap: use cases, mappers
viewModel / viewModelOfandroidx.lifecycle.ViewModel subclasses, resolved with koinViewModel()
named("...")Two bindings of one type (named("plain") and named("authenticated") clients)
  • singleOf(::X) resolves every constructor parameter by type. When one needs a qualifier or a value, write the lambda: single { X(client = get(named("authenticated")), pageSize = 20) }.
  • includes(otherModule) lets a feature aggregator pull in its sub-modules.
  • Never call get() at module level or inside a callback that runs later — only inside a definition lambda, where it resolves when the instance is built.

3. Platform modules

// commonMain — di/PlatformModule.kt
expect val platformModule: Module

// androidMain — di/PlatformModule.android.kt
actual val platformModule: Module = module {
    single<SecureStore> { AndroidSecureStore(context = androidContext()) }
    single { databaseBuilder(context = androidContext()) }
}

// iosMain — di/PlatformModule.ios.kt
actual val platformModule: Module = module {
    single<SecureStore> { KeychainSecureStore(service = "com.example.app.session") }
    single { databaseBuilder() }
}

Bind an interface from commonMain to a platform class here. androidContext() is only available in Android code and only after androidContext(...) was passed to Koin. Shared code never sees Context — it sees the interface.

4. Start Koin — once, in a fixed order

Koin resolves lazily, so module order rarely matters for plain lookups. The start-up sequence does matter, and reordering it is a classic source of launch crashes:

  1. Initialise anything definitions read outside Koin — a static platform-context holder used by expect factories, crash reporting, feature flags.
  2. Initialise the logger (Kermit, Napier) — definitions that log while being built, and the HTTP logging bridge, otherwise log into a logger that does not exist yet, or bypass its redaction.
  3. startKoin with infrastructure modules first and app modules last. Order inside modules(...) matters in two cases: an override (the last definition of a type + qualifier wins) and createdAtStart singletons, which are built at the end of startKoin.
// commonMain — di/InitKoin.kt
fun initKoin(config: KoinAppDeclaration? = null): KoinApplication = startKoin {
    config?.invoke(this)
    modules(appModules())
}
// androidMain (app module) — ExampleApplication.kt
class ExampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        AppLogging.init(isDebug = BuildConfig.DEBUG)          // 1 + 2: everything Koin definitions use
        initKoin {                                            // 3
            androidContext(this@ExampleApplication)
            androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
        }
    }
}
// iosMain — di/KoinIos.kt
@OptIn(ExperimentalNativeApi::class)              // kotlin.native.Platform
fun initKoinIos() {
    AppLogging.init(isDebug = Platform.isDebugBinary)
    initKoin()
}
// iosApp/iOSApp.swift
import Shared

@main
struct iOSApp: App {
    init() {
        KoinIosKt.doInitKoinIos()   // file KoinIos.kt → class KoinIosKt; "init…" gains a "do" prefix
    }
    var body: some Scene { WindowGroup { ContentView() } }
}
  • The Swift name follows the Kotlin file name. Check the generated header (Shared.framework/Headers) if it does not compile; tools such as SKIE can change how top-level functions are exposed.
  • Start Koin before the first Compose MainViewController() or any Swift call into Koin-backed code.
  • AppLogging and Platform.isDebugBinary stand for whatever the project already has.

5. ViewModels in Compose Multiplatform

// commonMain — profile/ui/ProfileScreen.kt
@Composable
fun ProfileRoute(profileId: String, viewModel: ProfileViewModel = koinViewModel { parametersOf(profileId) }) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    ProfileScreen(state = state, onRetry = viewModel::retry)
}
  • Import org.koin.compose.viewmodel.koinViewModel.
  • viewModelOf(::ProfileViewModel) resolves a String constructor parameter from parametersOf; for several parameters of the same type use the lambda form viewModel { (profileId: String) -> ProfileViewModel(profileId, get()) }.
  • Koin 4 resolves a SavedStateHandle constructor parameter from the ViewModel's creation extras.
  • koinViewModel() scopes to the nearest ViewModelStoreOwner — inside a navigation destination that is the back-stack entry, so the ViewModel lives as long as the screen.

6. Dependencies in Swift

Swift cannot call Koin's reified get<T>(). Expose a small KoinComponent facade from iosMain:

// iosMain — di/ProfileDependencies.kt
class ProfileDependencies : KoinComponent {
    fun profileRepository(): ProfileRepository = get()
    fun getProfileUseCase(): GetProfileUseCase = get()
}
let getProfile = ProfileDependencies().getProfileUseCase()

Keep the facade narrow — one per feature, returning interfaces. A shared ViewModel handed to Swift needs an owner that clears it when the view goes away, or its viewModelScope never cancels; see kmp-swiftui-interop.

7. Scopes — for state that must die before the process

A logged-in user's caches must not survive logout. Either reset single holders explicitly on logout, or use a Koin scope and close it:

val sessionModule = module {
    scope(named("session")) {
        scoped { ProfileCache() }
    }
}

// on sign-in
val sessionScope = getKoin().getOrCreateScope(scopeId = "session", qualifier = named("session"))
val cache: ProfileCache = sessionScope.get()

// on sign-out
sessionScope.close()          // every scoped instance is released

Anything that outlives the scope must not hold a reference to a scoped instance.

8. Verify the graph and test with fakes

Verification and override patterns: references/testing.md. In short:

  • A JVM test (androidUnitTest/androidHostTest or jvmTest) calls module.verify(extraTypes = ...) for each module — verify() lives in koin-test's JVM source set. checkModules() is deprecated.
  • Tests that start Koin call stopKoin() in @AfterTest. Prefer constructing the class under test with fakes directly; start Koin only to test wiring.

Quick reference

TaskAPI
Bind interfacesingleOf(::Impl) bind Repo::class or single<Repo> { Impl(get()) }
Qualified dependencysingle(named("authenticated")) { ... } + get(named("authenticated"))
Use casefactoryOf(::GetProfileUseCase)
ViewModelviewModelOf(::ProfileViewModel) + koinViewModel()
ViewModel parameterkoinViewModel { parametersOf(id) }
Platform bindingexpect val platformModule: Module + actual val per platform
Android startinitKoin { androidContext(this@App) } in Application.onCreate
iOS startKoinIosKt.doInitKoinIos() in the SwiftUI App.init
Swift accessKoinComponent facade in iosMain
Already started?KoinPlatform.getKoinOrNull() != null
Test cleanupstopKoin() in @AfterTest

Verify

Report each check as PASS, FAIL or NOT RUN (with the reason). A graph that compiles can still fail at the first get().

./gradlew :shared:testDebugUnitTest --tests "*KoinModulesTest*"   # verify() test (or testAndroidHostTest / jvmTest)
./gradlew :shared:allTests
./gradlew :composeApp:assembleDebug
./gradlew :shared:linkDebugFrameworkIosSimulatorArm64              # Swift-visible facades compile into the framework
grep -rn "startKoin" --include=*.kt . | grep -v Test               # exactly one production call site

Then launch the app on Android and on the iOS simulator and open one screen per feature you wired — resolution errors surface on first use, not at start.

Common mistakes

MistakeWhy it bitesFix
startKoin in both Application and a shared helper, or in every testKoinApplicationAlreadyStartedExceptionOne initKoin; stopKoin() after each test
Logger or platform holder initialised after startKoinEager or early-built instances crash or log unredactedFixed order: platform init → logger → Koin
Swift calls shared code before doInitKoinIos()KoinApplication has not been started, iOS onlyStart in App.init / didFinishLaunching
Qualifier string typoNoDefinitionFoundException on first use onlyConstants for qualifier names; verify() test
singleOf(::X) when X needs a qualified dependencyResolves the unqualified binding — or failsLambda definition with get(named(...))
Repository declared with factoryA new instance per injection; caches and in-flight refreshes are not sharedsingle
Two modules both define the same type, unintentionallySilent override: the last one loaded winsSearch before adding; allowOverride(false) in a test to catch it
get() captured inside a lambda that runs laterResolves against whatever graph exists then, or crashes after stopKoinResolve in the definition, pass the instance
Context or UIViewController injected into commonMain classesBreaks the shared buildInterface in common, platform binding in platformModule
Old org.koin.compose.viewmodel.dsl.viewModelOf importDeprecated in Koin 4org.koin.core.module.dsl.viewModelOf
Tests share a started KoinOrder-dependent failuresFakes via constructors; stopKoin() in @AfterTest

Related skills

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.