Ktor and Dependency Injection

Published 2024-04-19
Last week (   • Kotlin Coroutines and Loom  ) we looked at how we can use Loom virtual threads to enable thousands of simultaneous connections to a Kotlin server without coroutines.

Even so loyal viewer David remains unconvinced that he can replace Ktor, JetBrains’ server offering, with http4k, the plucky British underdog. So I decided to take a look at Ktor to understand why.

I started by looking at Ktor (ktor.io/) example code. The one I picked (ktor.io/docs/server-create-http-apis.html) doesn’t have good test coverage, so I thought that I’d add some. This revealed that the code relies on global variables for state, so in the best yak-shaving tradition, I started by fixing that.

Looking back, I find it interesting that I didn’t use the phrase Dependency Injection at all during filming. Perhaps that’s because I’m not using a framework, perhaps because passing dependencies to constructors is just, erm, usual. Whatever the reason, stay tuned to see how to inject dependencies to make an application testable.

In this episode

00:01:05 Creating HTTP APIs example
00:02:05 Look at the tests
00:02:45 Add a test case for CustomerRoutes
00:04:04 How do the routes see the customers?
00:04:48 Ah, a global mutable variable
00:06:20 The third test shows our problem
00:07:12 Global state is preventing testing
00:08:27 Push the reference to the global out of our code
00:09:05 IntelliJ Introduce Parameter Bug
00:09:17 What is calling our configuration code then?
00:10:07 AI Assistant can fix things to be more explicit
00:11:39 So now we can move the state injection to the top level
00:12:13 Our tests though are not properly wired up
00:14:19 Remove duplication from the testApplication setup
00:16:27 Now make orders not global too
00:19:01 Stop using the production orders in the test
00:19:41 Checkin


If you like this, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (java-to-kotlin.dev/). It's about far more than just the syntax differences between the languages - it shows how to upgrade your thinking to a more functional style.

All Comments (4)
  • This example solves the problem perfectly but curious what situations you might reach for a DI system?
  • @gianpaul18
    first, duncan good job ! thanks for the video