Skip to content

相依性解析 ​

必要相依性:io.ktor:ktor-server-di

程式碼範例: server-di

在你註冊相依性之後,你可以從相依注入 (DI) 容器中解析它們,並將它們注入到應用程式程式碼中。

你可以使用屬性委託或直接解析,明確地從 DI 容器中解析相依性。

使用屬性委託 ​

使用屬性委託時,相依性僅會在啟動驗證階段進行解析:

kotlin
val service: GreetingService by dependencies

使用直接解析 ​

直接解析會立即傳回相依性,或者暫停直到其可用為止:

kotlin
val service = dependencies.resolve<GreetingService>()

參數解析 ​

解析建構函式或函式時,Ktor 會使用 DI 容器來解析參數。預設情況下,參數是依型別來解析的。

如果基於型別的解析不足以滿足需求,你可以使用註解來明確綁定參數。

使用具名相依性 ​

使用 @Named 註解來解析以指定名稱註冊的相依性:

kotlin
fun Application.userRepository(@Named("mongo") database: Database) {
    // 使用名為 "mongo" 的相依性
}

使用配置屬性 ​

使用 @Property 註解從應用程式配置中注入值:

kotlin
package com.example

import io.ktor.server.plugins.di.annotations.Property

fun provideDatabase(
    @Property("database.connectionUrl") connectionUrl: String
): Database = PostgresDatabase(connectionUrl)

open class UserRepository(val db: Database)

在上述範例中,database.connectionUrl 屬性是從應用程式配置中解析而來的:

yaml
database:
  connectionUrl: postgres://localhost:5432/admin

非同步相依性解析 ​

為了支援非同步載入,你可以使用 suspend 函式:

kotlin
data class EventsConnection(val connected: Boolean)

suspend fun Application.installEvents() {
    val conn: EventsConnection = dependencies.resolve()
    log.info("Events connection ready: $conn")
}

suspend fun Application.loadEventsConnection() {
    dependencies.provide {
        delay(200) // 模擬非同步工作
        EventsConnection(true)
    }
}

DI 外掛程式會自動掛起 resolve() 呼叫,直到所有相依性準備就緒。

將相依性注入應用程式模組 ​

你可以透過在模組函式中指定參數,將相依性直接注入應用程式模組中。Ktor 將根據型別比對從 DI 容器中解析這些相依性。

首先,在你的設定檔中的 ktor.application.dependencies 群組中註冊你的相依性提供者:

yaml
ktor:
  application:
    dependencies:
      - com.example.PrintStreamProviderKt.stdout
    modules:
      - com.example.LoggingKt.logging

定義相依性提供者以及帶有你欲注入相依性參數的模組函式。接著,你就可以直接在模組函式中使用已注入的相依性:

kotlin
package com.example

import java.io.PrintStream

fun stdout(): () -> PrintStream = { System.out }
kotlin
package com.example

import io.ktor.server.application.*
import io.ktor.server.plugins.di.dependencies
import java.io.PrintStream

class Logger(private val out: PrintStream) {
     fun log(message: String) {
        out.println("[LOG] $message")
    }
}

fun Application.logging(printStreamProvider: () -> PrintStream) {
    dependencies {
        provide<Logger> {
            Logger(printStreamProvider())
        }
    }
}

進階相依性解析 ​

選用與可為 null 的相依性 ​

使用可為 null 的型別來從容處理選用相依性:

kotlin
// 使用屬性委託
val config: Config? by dependencies

// 使用直接解析
val config = dependencies.resolve<Config?>()

共變泛型 ​

Ktor 的 DI 系統支援型別共變性 (covariance),當型別參數為共變時,允許將值作為其超型別之一進行注入。這對於處理子型別的集合和介面特別有用。

kotlin
dependencies {
  provide<List<String>> { listOf("one", "two") }
}

// 由於支援型別參數共變性,這將可以正常運作
val stringList: List<CharSequence> by dependencies
// 這也將可以正常運作
val stringCollection: Collection<CharSequence> by dependencies

共變性也適用於非泛型超型別:

kotlin
dependencies {
    provide<BufferedOutputStream> { BufferedOutputStream(System.out) }
}

// 這是可行的,因為 BufferedOutputStream 是 OutputStream 的子型別
val outputStream: OutputStream by dependencies

限制 ​

雖然 DI 系統支援泛型型別的共變性,但目前不支援跨型別引數子型別來解析參數化型別。這意味著你無法使用比已註冊型別更具體或更廣義的型別來取得相依性。

例如,以下程式碼將無法解析:

kotlin
dependencies {
    provide<Sink<CharSequence>> { CsqSink() }
}

// 無法解析
val charSequenceSink: Sink<String> by dependencies