Ktor 3.4.1 Help

Resource lifecycle management

The dependency injection (DI) plugin handles lifecycle and cleanup automatically when the application shuts down.

AutoCloseable support

By default, any dependency that implements AutoCloseable is automatically closed when your application stops:

class DatabaseConnection : AutoCloseable { override fun close() { // Close connections, release resources } } dependencies { provide<DatabaseConnection> { DatabaseConnection() } }

Custom cleanup logic

You can define custom cleanup logic by specifying a cleanup function:

dependencies { provide<ResourceManager> { ResourceManagerImpl() } cleanup { manager -> manager.releaseResources() } }

Scoped cleanup with key

Use key to manage named resources and their cleanup:

dependencies { key<Closer>("second") { provide { CustomCloser() } cleanup { it.closeMe() } } }

Dependencies are cleaned up in reverse order of declaration to ensure proper teardown.

27 February 2026