Antonio AcuƱa Prieto
11/07/2024, 8:36 PMby inject<T>()
all the time it's too verbose
in ktor 2.X.X I had this function with Kodein:
routing {
post("sign-up", executeInvoke<SignUp>())
}
inline fun <reified T : Handler> executeInvoke(): suspend PipelineContext<Unit, ApplicationCall>.(Unit) -> Unit = {
val handler by closestDI().instance<T>()
handler(this.call)
}
but I can't make it work with Ktor 3.X.Xasdf asdf
11/08/2024, 5:35 AMrocketraman
11/08/2024, 3:25 PMAntonio AcuƱa Prieto
11/10/2024, 9:18 AMrocketraman
11/10/2024, 3:39 PMfun main() {
// the map could come from DI
val handlerFactory = HandlerFactory(
mapOf(
HelloHandler::class to HelloHandler(),
)
)
Server(handlerFactory).start()
}
class Server(private val handlerFactory: HandlerFactory) {
fun start() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = { module(handlerFactory) })
.start(wait = true)
}
}
class HandlerFactory(val handlers: Map<KClass<out Handler>, Handler>) {
inline fun <reified T : Handler> handlerOf(): Handler {
return handlers[T::class] ?: throw IllegalArgumentException("No handler found for ${T::class}")
}
}
fun Application.module(handlerFactory: HandlerFactory) {
configureRouting(handlerFactory)
}
fun Application.configureRouting(handlerFactory: HandlerFactory) {
routing {
get("/") {
handlerFactory.handlerOf<HelloHandler>().invoke(call)
}
}
}