Dependency registration
Ktor’s dependency injection (DI) container needs to know how to create objects that your application depends on. This process is called dependency registration.
Basic dependency registration
Basic dependency registration is done in code, typically within an Application module using the dependencies {} block.
You can register dependencies by providing lambdas, function references, class references, or constructor references:
Use a lambda
Use a lambda when you want full control over how an instance is created:
This registers a provider for GreetingService. Whenever GreetingService is requested, the lambda is executed to create an instance.
Use a constructor reference
If a class can be created using its constructor and all constructor parameters are already registered in the DI container, you can use a constructor reference.
This tells your application to use the constructor of GreetingServiceImpl, and let DI resolve its parameters.
Use a class reference
You can register a concrete class without binding it to an interface:
In this case, the dependency is resolved by its BankServiceImpl type. This is useful when the implementation type is injected directly and no abstraction is required.
Use a function reference
You can register a function that creates and returns an instance:
The DI container resolves the function parameters and uses the return value as the dependency instance.
Use a factory lambda
You can register a function itself as a dependency:
This registers a function that can be injected and called manually to create new instances.
Named dependency registration
You can assign a name to a dependency at registration time to distinguish multiple providers of the same type.
This is useful when you need to register more than one implementation or instance for a single type and select between them explicitly during resolution.
To assign a name to a dependency, pass the name as the first argument to the provide() function:
Named dependencies must be resolved explicitly using the @Named annotation.
Configuration-based dependency registration
You can configure dependencies declaratively using classpath references in your configuration file. You can list a function that returns an object, or a class with a resolvable constructor.
List the dependencies under the ktor.application.dependencies group in your configuration file:
Ktor resolves function and constructor parameters automatically using the DI container.