Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split up :di-kodein into simple and advanced samples #62

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions other/di-kodein-advanced/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Kodein-DI

Sample project for [Ktor](https://ktor.io) showing how to use [Kodein DI](https://kodein.org/Kodein-DI/) within Ktor.

## Running

Execute this command in the repository's root directory to run this sample:

```bash
./gradlew :di-kodein-advanced:run
```

And navigate to [http://localhost:8080/users/](http://localhost:8080/users/) to see the sample home page.
37 changes: 37 additions & 0 deletions other/di-kodein-advanced/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

apply plugin: 'kotlin'
apply plugin: 'application'

mainClassName = "io.ktor.samples.kodein.KodeinAdvancedApplicationKt"

sourceSets {
main.kotlin.srcDirs = [ 'src' ]
test.kotlin.srcDirs = [ 'test' ]
main.resources.srcDirs = [ 'resources' ]
}

repositories {
jcenter()
maven { url "https://dl.bintray.com/kotlin/ktor" }
}

dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile "io.ktor:ktor-server-netty:$ktor_version"
compile "ch.qos.logback:logback-classic:$logback_version"

compile "io.ktor:ktor-html-builder:$ktor_version"
compile "io.ktor:ktor-locations:$ktor_version"

compile 'org.kodein.di:kodein-di-generic-jvm:5.2.0'

testCompile "io.ktor:ktor-server-test-host:$ktor_version"
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import io.ktor.server.netty.*
import kotlinx.html.*
import org.kodein.di.*
import org.kodein.di.generic.*
import java.util.*

/**
* Entry point of the embedded-server sample program:
Expand All @@ -27,18 +26,22 @@ import java.util.*
fun main(args: Array<String>) {
embeddedServer(Netty, port = 8080) {
kodeinApplication { application ->
application.apply {
// This adds automatically Date and Server headers to each response, and would allow you to configure
// additional headers served to each response.
install(DefaultHeaders)
}

bindSingleton { Users.Repository() }
bindSingleton { Users.Controller(it) }
advancedApplication(application)
}
}.start(wait = true)
}

internal fun Kodein.MainBuilder.advancedApplication(application: Application) {
application.apply {
// This adds automatically Date and Server headers to each response, and would allow you to configure
// additional headers served to each response.
install(DefaultHeaders)
}

bind<Users.IRepository>() with singleton { Users.Repository() }
bind<Users.Controller>() with singleton { Users.Controller(kodein) }
}

/**
* Users Controller, Router and Model. Can move to several files and packages if required.
*/
Expand All @@ -52,7 +55,7 @@ object Users {
/**
* [Repository] instance provided by [Kodein]
*/
val repository: Repository by instance()
private val repository: IRepository by instance()

/**
* Registers the routes related to [Users].
Expand Down Expand Up @@ -94,16 +97,23 @@ object Users {
data class User(val name: String)

/**
* [Users.Repository] that will handle operations related to the users on the system.
* Repository that will handle operations related to the users on the system.
*/
interface IRepository {
fun list(): List<User>
}

/**
* Fake in-memory implementation of [Users.IRepository] for demo purposes.
*/
class Repository {
class Repository : IRepository {
private val initialUsers = listOf(User("test"), User("demo"))
private val usersByName = LinkedHashMap<String, User>(initialUsers.associateBy { it.name })
private val usersByName = initialUsers.associateBy { it.name }

/**
* Lists the available [Users.User] in this repository.
*/
fun list() = usersByName.values.toList()
override fun list() = usersByName.values.toList()
}

/**
Expand Down Expand Up @@ -144,7 +154,7 @@ fun Application.kodeinApplication(

/**
* Creates a [Kodein] instance, binding the [Application] instance.
* Also calls the [kodeInMapper] to map the Controller dependencies.
* Also calls the [kodeinMapper] to map the Controller dependencies.
*/
val kodein = Kodein {
bind<Application>() with instance(application)
Expand All @@ -155,13 +165,21 @@ fun Application.kodeinApplication(
* Detects all the registered [KodeinController] and registers its routes.
*/
routing {
for (bind in kodein.container.tree.bindings) {
val bindClass = bind.key.type.jvmType as? Class<*>?
if (bindClass != null && KodeinController::class.java.isAssignableFrom(bindClass)) {
val res by kodein.Instance(bind.key.type)
println("Registering '$res' routes...")
(res as KodeinController).apply { registerRoutes() }
}
fun findControllers(kodein: Kodein): List<KodeinController> =
kodein
.container.tree.bindings.keys
.filter { bind ->
val clazz = bind.type.jvmType as? java.lang.Class<*> ?: return@filter false
KodeinController::class.java.isAssignableFrom(clazz)
}
.map { bind ->
val res by kodein.Instance(bind.type)
res as KodeinController
}

findControllers(kodein).forEach { controller ->
println("Registering '$controller' routes...")
controller.apply { registerRoutes() }
}
}
}
Expand All @@ -174,7 +192,7 @@ abstract class KodeinController(override val kodein: Kodein) : KodeinAware {
/**
* Injected dependency with the current [Application].
*/
val application: Application by instance()
private val application: Application by instance()

/**
* Shortcut to get the url of a [TypedRoute].
Expand All @@ -187,13 +205,6 @@ abstract class KodeinController(override val kodein: Kodein) : KodeinAware {
abstract fun Routing.registerRoutes()
}

/**
* Shortcut for binding singletons to the same type.
*/
inline fun <reified T : Any> Kodein.MainBuilder.bindSingleton(crossinline callback: (Kodein) -> T) {
bind<T>() with singleton { callback([email protected]) }
}

/**
* Interface used for identify typed routes annotated with [Location].
*/
Expand Down
93 changes: 93 additions & 0 deletions other/di-kodein-advanced/test/KodeinAdvancedApplicationTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package io.ktor.samples.kodein

import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.withTestApplication
import org.kodein.di.generic.bind
import org.kodein.di.generic.singleton
import kotlin.test.Test
import kotlin.test.assertEquals

/**
* Integration tests for the [advancedApplication] module from KodeinAdvancedApplication.
*/
class KodeinAdvancedApplicationTest {

@Test
fun `get user`() = withTestApplication<Unit>(
{
kodeinApplication { advancedApplication(it) }
}
) {
handleRequest { method = HttpMethod.Get; uri = "/users/fake" }.apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(
"""
<!DOCTYPE html>
<html>
<body>
<h1>fake</h1>
</body>
</html>
""".trimIndent() + "\n",
response.content
)
}
}

@Test
fun `get default users`() = withTestApplication<Unit>(
{
kodeinApplication { advancedApplication(it) }
}
) {
handleRequest { method = HttpMethod.Get; uri = "/users/" }.apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(
"""
<!DOCTYPE html>
<html>
<body>
<ul>
<li><a href="/users/test">test</a></li>
<li><a href="/users/demo">demo</a></li>
</ul>
</body>
</html>
""".trimIndent() + "\n",
response.content
)
}
}

// Note: a JVM bug prevents us from using `nice test names` when there's a local class defined in it.
@Test
fun testGetFakeUsers() = withTestApplication<Unit>(
{
class FakeRepository : Users.IRepository {
override fun list() = listOf(Users.User("fake"))
}
kodeinApplication {
advancedApplication(it)
bind<Users.IRepository>(overrides = true) with singleton { FakeRepository() }
}
}
) {
handleRequest { method = HttpMethod.Get; uri = "/users/" }.apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(
"""
<!DOCTYPE html>
<html>
<body>
<ul>
<li><a href="/users/fake">fake</a></li>
</ul>
</body>
</html>
""".trimIndent() + "\n",
response.content
)
}
}
}
6 changes: 2 additions & 4 deletions other/di-kodein/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ repositories {
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile "io.ktor:ktor-server-netty:$ktor_version"
compile "io.ktor:ktor-html-builder:$ktor_version"
compile "io.ktor:ktor-locations:$ktor_version"
compile "io.ktor:ktor-html-builder:$ktor_version"
compile "ch.qos.logback:logback-classic:$logback_version"

compile 'org.kodein.di:kodein-di-generic-jvm:5.2.0'

testCompile "io.ktor:ktor-server-test-host:$ktor_version"
}

3 changes: 2 additions & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ module('other', 'filelisting')
module('other', 'structured-logging')
module('other', 'client-multipart')
module('other', 'client-tools')
// module('other', 'di-kodein')
module('other', 'di-kodein')
module('other', 'di-kodein-advanced')
module('other', 'reverse-proxy')
module('other', 'reverse-proxy-ws')
module('other', 'redirect-with-exception')
Expand Down