gps
08/10/2020, 9:26 AMEric Grimsborn
08/10/2020, 10:19 AMgps
08/10/2020, 11:05 AMEric Grimsborn
08/10/2020, 12:10 PMimport io.ktor.application.ApplicationCall
import io.ktor.application.ApplicationCallPipeline
import io.ktor.application.ApplicationFeature
import io.ktor.application.call
import io.ktor.util.AttributeKey
import io.ktor.util.pipeline.PipelineContext
class DiInstance
val DIAttributeKey = AttributeKey<DiInstance>("dependency-injection")
class DIFeature(val configuration: Configuration) {
class Configuration {
var di: DiInstance? = null
}
// Body of the feature
private fun intercept(context: PipelineContext<Unit, ApplicationCall>) {
// Make the di instance avaliable on the call
configuration.di?.let {
context.call.attributes.put(DIAttributeKey, it)
}
}
companion object Feature : ApplicationFeature<ApplicationCallPipeline, Configuration, DIFeature> {
override val key = AttributeKey<DIFeature>("DI Feature")
override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): DIFeature {
// Call user code to configure a feature
val configuration = Configuration().apply(configure)
if (configuration.di == null) {
throw IllegalStateException("Must supply instance of DI")
}
// Create a feature instance
val feature = DIFeature(configuration)
// Install an interceptor that will be run on each call and call feature instance
pipeline.intercept(ApplicationCallPipeline.Call) {
feature.intercept(this)
}
// Return a feature instance so that client code can use it
return feature
}
}
}
/**
* install(DIFeature){
* di = DiInstance()
* }
*/
Eric Grimsborn
08/10/2020, 12:52 PMval di: DiInstance = call.attributes[DIAttributeKey]
in your request handlersgps
08/11/2020, 12:35 AMcall
, I wouldn't be able to inject request specific stuff in there. If I had access to call
, I wouldn't need the DI at all - I'd use call.attributes
directly as you've done above.jorge.rego
08/12/2020, 7:49 AM