Skip to content

Kodein 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.

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

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

Install the Kodein plugin

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

import dev.programadorthi.routing.kodein.DIPlugin
// ...

val router = routing {
    install(DIPlugin) {
        // declare your kodein binds here
    }
}

Getting instances

import dev.programadorthi.routing.kodein.ext.instance
// ...

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

Getting the DI instance

import dev.programadorthi.routing.kodein.closestDI
// ...

val router = routing {
    handle(path = "...") {
        closestDI() // lazy di instance
    }
}

Isolated DI Graph

import dev.programadorthi.routing.kodein.DIPlugin
import dev.programadorthi.routing.kodein.subDI
// ...

val parent = routing {
    install(DIPlugin) {
        // declare your kodein binds here
    }
}

val feature = routing(parent = parent, ...) {
    subDI {
        // exclusive feature graph that extends parent graph
    }
}

Reusing an existent graph

import dev.programadorthi.routing.kodein.DIPlugin
import org.kodein.di.DI
// ...

val externalDI: DI = // ...

val router = routing {
    install(DIPlugin) {
        extend(externalDI)
    }
}