Ktor 3.4.1 Help

Dependency injection

Dependency injection (DI) is a design pattern that helps you supply components with the dependencies they require. Instead of creating concrete implementations directly, modules depend on abstractions, and a DI container is responsible for constructing and providing the appropriate instances at runtime. This separation reduces coupling, improves testability, and makes it easier to replace or reconfigure implementations without modifying existing code.

Ktor provides a built‑in DI plugin that lets you register services and configuration objects once and access them throughout your application. You can inject these dependencies into modules, plugins, routes, and other Ktor components in a consistent, type‑safe way. The plugin integrates with the Ktor application lifecycle and supports scoping, structured configuration, and automatic resource management, making it easier to organize and maintain application‑level services.

Add dependencies

To use DI, include the ktor-server-di artifact in your build script:

implementation("io.ktor:ktor-server-di:$ktor_version")
implementation "io.ktor:ktor-server-di:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-di-jvm</artifactId> <version>${ktor_version}</version> </dependency>

How dependency injection works in Ktor

In Ktor, dependency injection is a single, integrated process that consists of two closely related steps:

These steps are handled by a single DI container.

To begin using dependency injection in your application, start with registering dependencies. Once dependencies are declared, continue with resolving dependencies.

Supported features

The DI plugin supports a range of features intended to cover common application needs:

Configuration and lifecycle behavior

The behavior of the DI container can be customized using configuration options. These options control how dependency keys are matched, how conflicts are handled, and how resolution behaves in advanced scenarios.

For configuration details, see Configure the DI plugin.

For resource cleanup and shutdown behavior, see Resource lifecycle management.

Testing with dependency injection

The DI plugin integrates with Ktor’s testing utilities and supports overriding dependencies, loading configuration, and controlling conflict behavior in test environments.

For more information and examples, see Testing with dependency injection.

27 February 2026