Introduction
Modules
Group related classes, and say what is shared.
Why modules
An application has dozens of classes. A module is a folder-sized unit of the application: users, orders, payments. It lists the classes that belong together and says which of them other modules may use. Modules keep a growing application understandable: you can see what orders needs from payments by reading two lines, not by searching the project.
@Module(
imports = [AuthModule::class], // modules whose exports I use
providers = [UserService::class, InMemoryUserRepository::class], // classes I own that can be injected
controllers = [UserController::class], // classes that receive requests (routes, resolvers, gateways, commands)
exports = [UserService::class], // what other modules may use from me
)
class UsersModule| Part | Meaning |
|---|---|
imports | other modules I depend on; I can use what they export |
providers | services, repositories and helpers created and owned by this module |
controllers | classes that handle input: HTTP controllers, GraphQL resolvers, WebSocket gateways, CLI commands |
exports | the subset of my providers (or modules I imported) that others may inject |
global = true | every module may use my exports without importing me |
Sharing between modules
Say orders needs to look up users:
@Module(providers = [UserService::class], exports = [UserService::class]) class UsersModule
@Module(imports = [UsersModule::class], providers = [OrderService::class], controllers = [OrderController::class]) class OrdersModule
@Injectable class OrderService(private val users: UserService) // allowed: OrdersModule imports UsersModule, which exports itIf UsersModule forgot to export UserService, the build fails with a message naming exactly what to add:
OrderService (in OrdersModule) needs UserService, but it is not visible in OrdersModule.
Provided by UsersModule, which OrdersModule imports, but UsersModule does not export it.
Fix: add UserService to UsersModule's `exports`.This check (every dependency must be visible from the module that declares the provider), plus checks for circular imports, circular constructor dependencies, duplicate routes within a module and unknown parameters in route paths, run at compile time for modules written with @Module. A mistake never reaches production.
Difference from NestJS
Providers are unique per type across the whole application, not per module: two modules cannot each own a different instance of the same class. Visibility between modules is enforced when you build; at run time every provider is available to the container.
Organising a real application
A common layout is one module per feature, plus a few shared ones:
src/main/kotlin/com/acme/shop/
AppModule.kt imports every feature module and the infrastructure modules
users/ UsersModule.kt UserController.kt UserService.kt UserRepository.kt
orders/ OrdersModule.kt ...
payments/ PaymentsModule.kt ...
shared/ guards, filters, interceptors, small utilities (a SharedModule if they are providers)- Keep a feature module small and cohesive; split when it passes a few thousand lines or two teams edit it.
- Export only what other modules need (usually one service, a facade), and keep repositories private to their module. That makes the module boundary real.
- Put a class used by many modules (a logger wrapper, a clock) in a module marked
global = true, sparingly: global modules hide dependencies. - Generate the files with
kest g resource orders; it adds the new module to the nearest parent for you.
Dynamic modules
Some modules need values only the application knows: a database URL, a secret key. These are dynamic modules, configured with forRoot or register and a block:
Kest.run<AppModule> {
import(
ConfigModule.forRoot { envFiles = listOf(".env") },
JwtModule.register { secret = System.getenv("JWT_SECRET"); expiresIn = Duration.ofHours(1) },
ThrottlerModule.forRoot { limit = 100 },
CacheModule.register { ttl = Duration.ofSeconds(30) },
)
}You can write your own: see Dynamic modules.
Standalone applications
val app = Kest.create<AppModule>() // the container only: no web serverUse it for workers, scripts, command-line tools and tests (Commander, Standalone applications). A hybrid application runs http { } and microservice(...) on one container.
Writing your own configurable module
This is the NestJS pattern of a module that imports ConfigModule, configures another module with forRootAsync({ inject: [ConfigService], useFactory }), and exports it:
// NestJS
@Module({})
export class PostgresModule {
static forRoot(options: PostgresModuleOptions = {}): DynamicModule {
return { module: PostgresModule, global: options.isGlobal ?? true,
imports: [ConfigModule, TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: buildPostgresOptions })],
exports: [TypeOrmModule] };
}
}// Kest
@Provided data class PostgresModuleOptions(val isGlobal: Boolean = true)
@Module
class PostgresModule {
companion object {
fun forRoot(options: PostgresModuleOptions = PostgresModuleOptions()) = DynamicModule.create(PostgresModule::class) {
global = options.isGlobal
imports(
ConfigModule.forRoot(),
OrmModule.forRootAsync { config: ConfigService -> buildPostgresOptions(config) },
)
provide(options) // a value
provide<Pool> { r -> Pool(r.get(ConfigService::class).getOrThrow<String>("pg.url")) } // useFactory, with the container
exports(OrmModule::class)
}
}
}
Kest.run<AppModule> { import(PostgresModule.forRoot()) }imports(...)takes other dynamic modules. They are registered with yours, and a module imported by several of them is registered once.provide(value),provide<T> { r -> ... }andprovide(Token) { r -> ... }areuseValueanduseFactory.globalandexportsare recorded but do not hide anything: every provider is already visible to every module, because the module graph is checked at compile time rather than enforced at run time. Types supplied this way are marked@Providedso the compiler knows they exist.- Java:
DynamicModule.create(PostgresModule.class, b -> { b.imports(...); b.provide(...); }).
Common mistakes
| Mistake | Result |
|---|---|
| a provider is in no module | build error: nothing provides it |
a controller listed under providers | it is created but its routes are not registered: list it under controllers |
| importing a module only to reach one class, without exports | build error naming the missing export |
| two modules importing each other | build error: Circular module import: A -> B -> A. Extract the shared part into a third module, or mark one side forwardImports = [...] (Circular dependency) |
| the same class provided by two modules | DuplicateProviderException: a class has exactly one owner |