/kodein-application

Set of helper functions to create applications with kodein-di as a base

Primary LanguageKotlinMIT LicenseMIT

Kodein Application

Build CodeFactor ktlint

Maven Central GitHub

Warning
From version 0.5.0 all package names have been renamed to match new artifact group id.

Extension functions that ease making applications with Kodein container as a core.

Kodein DI support

Kodein DI version Kodein Application version

7

>= 0.6

6

<= 0.5

Example

const val MODULE_HTTP_API = "httpApi"

val httpApi = DI.Module(MODULE_HTTP_API) {
    bind<SomeHttpServer>(tag = MODULE_HTTP_API) with singleton {
        SomeHttpServer(serverConfig())
    }

    on(Start) {
        val server: SomeHttpServer = direct.instance(tag = MODULE_HTTP_API)

        server.start()
    }

    on(Stop) {
        val server: SomeHttpServer = direct.instance(tag = MODULE_HTTP_API)

        server.stop()
    }
}

val MyApplication = kodeinApplication {
    import(httpApi, allowOverride = true)
}

fun main() {
    MyApplication.run()

    // Remember to gracefully finish logging threads and flush buffers
    // Depends on your logging provider
    closeLoggers()
}

Testing

const val MODULE_TEST = "test"

val testConfiguration = DI.Module(MODULE_TEST) {
    bind<SomeHttpServer>(tag = MODULE_HTTP_API, overrides = true) with singleton {
        TestHttpServer(serverConfig())
    }
}

@Suppress("TestFunctionName")
fun TestApplication(extraConfig: DI.MainBuilder.() -> Unit = {}) = Kodein {
    extend(MyApplication, copy = Copy.All)
    import(testConfiguration, allowOverride = true)

    extraConfig()
}

internal class DeployControllerTest : DIAware {

    override val kodein = TestApplication() {
        // you can further configure it here with your test specific bindings and overrides
    }

    private val server: SomeHttpServer by instance(tag = MODULE_HTTP_API)

    @BeforeAll
    fun start() {
        server.start()
    }

    @AfterAll
    fun stop() {
        server.stop()
    }

    @Test
    fun someTest() = with(server) {
        // some test
    }
}