Ktor - dynamically install and uninstall modules?

The Ktor examples I see are all statically defined in the Kotlin code. I’d like to be able to load and unload web apps, sort of like you do in servlet containers like Tomcat, Wildfly. Is that possible?

In other words, how do you define something like this so that it can be uninstalled?

fun Application.mymodule() {
    routing {
        get("/") {
            call.respondText("Hello World!")
        }
    }
}

If not, I guess the only way to deploy new code is to kill the ktor process and start another one. ?

1 Like

I guess if you are referring to similar modules system loaded with NestJS, then the answer is yes. It can be dynamically loaded.

  1. Use Ktor’s Modules feature:
  • Declare module classes and include a module() function
  • Load modules at runtime via Application.modules.loadModules()
  • Ktor will initialize any module registered this way
  1. Manually load code using KClassLoader:
  • Get an instance of Ktor’s KClassLoader
  • Call loadClass() to dynamically load a Kotlin class
  • Create instances and access the module programmatically
  1. Use a library like KDi for dependency injection
  • Annotate classes with @Module and @Provides
  • Load modules and call configure() to initialize bindings
  • Retrieve instances from the injector as needed

In summary, Ktor supports dynamic module loading in multiple ways - built-in modules, manual class loading, and dependency injection libraries.

This allows initializing code and dependencies on the fly similar to NestJS. The main difference is Ktor is not opinionated so you have to wire up the module system yourself.

I hope that helps.