fun Route.withRequestContextCache( build: Route.() -> Unit ): Route { val route = this route.install(ContextCache) route.build() return route } val ContextCache = createRouteScopedPlugin( name = "ContextCache", createConfiguration = {}) { on(RequestContextCacheRouteHook) { call, proceed -> withContextCache { proceed() } } } internal object RequestContextCacheRouteHook : Hook Unit) -> Unit> { internal val RequestContextCachePhase: PipelinePhase = PipelinePhase("RequestContextCachePhase") override fun install( pipeline: ApplicationCallPipeline, handler: suspend (ApplicationCall, suspend () -> Unit) -> Unit, ) { pipeline.insertPhaseAfter(ApplicationCallPipeline.Plugins, RequestContextCachePhase) pipeline.intercept(RequestContextCachePhase) { handler(call, ::proceed) } } }