Skip to content

Koin Integration

Thiago Santos edited this page Aug 18, 2024 · 2 revisions

Important

This module is a case of studies that shows how you can extend Kotlin Routing to your context.

Koin module brings the power of dependency injection to get instances while handling to a route.

sourceSets {
    commonMain.dependencies {
        implementation("dev.programadorthi.routing:koin:$version")
    }
}

Install the Koin plugin

Installing the Koin tells the Routing how to provide a DI Graph to the routes that can get instances.

import dev.programadorthi.routing.koin.Koin
// ...

val router = routing {
    install(Koin) {
        setup {
            // add your Koin modules here
        }
    }
}

Getting instances

import dev.programadorthi.routing.koin.ext.inject
// ...

val router = routing {
    handle(path = "...") {
        val value: Type by inject()
    }
}

Getting the DI instance

import dev.programadorthi.routing.koin.ext.getKoin
// ...

val router = routing {
    handle(path = "...") {
        getKoin() // Koin instance
    }
}

Sharing same graph

import dev.programadorthi.routing.koin.ext.getKoin
import dev.programadorthi.routing.koin.Koin
// ...

val parent = routing {
    install(Koin) {
        setup {
            // add your Koin modules here
        }
    }
}

val feature = routing(parent = parent, ...) {
    // Getting parent Koin instance and loading feature modules
    getKoin().loadModules(...)
}

Reusing an existent graph

import dev.programadorthi.routing.koin.KoinIsolated
import org.koin.core.context.startKoin
// ...

val externalDI = startKoin {
    // ...
}

val router = routing {
    install(KoinIsolated) {
        setup(koinApplication = externalDI) {}
    }
}

Isolated graphs

import dev.programadorthi.routing.koin.Koin
import dev.programadorthi.routing.koin.KoinIsolated
// ...

val parent = routing {
    install(Koin) {
        setup {
            // parent graph don't know about feature graph
        }
    }
}

val feature = routing(parent = parent, ...) {
    install(KoinIsolated) {
        setup {
            // feature graph don't know about parent graph
        }
    }
}