Dependency injection
Manage dependencies through explicit providers, module scopes, and constructor bindings with LykosJS Dependency Injection.

Overview
LykosJS includes a built-in Dependency Injection (DI) system that manages class dependencies and their lifecycle. Instead of creating dependencies manually, you register providers and let the container resolve and inject them when needed.
The system is built around DIModule, bind(), and the dependency container. Each module has its own scope, allowing dependencies to be organized, imported, and selectively exported.
Creating a module
Every DI module extends DIModule. You can define its providers, controllers, routers, imported modules, exported tokens, and optional authentication configuration.
1import { DIModule } from 'lykosjs'2 3export class UsersModule extends DIModule {4 override providers = [UsersService]5 override controllers = [UsersController]6 override routers = [UsersRouter]7}DIModule properties
A module exposes the following properties:
providers
Registers injectable providers. A provider can be a class with no constructor dependencies or a provider created usingbind() or value().
1override providers = [2 UsersService,3 bind(EmailService, MailTransport),4 value(UserModel),5]controllers
Registers controller classes or explicitly bound controller providers. Use bind() when a controller has constructor dependencies.
1override controllers = [bind(UsersController, UsersService)]routers
Registers router classes or bound router providers. A router must implement a register(): void method. During module loading, LykosJS resolves each router and calls itsregister() method.
1override routers = [bind(UsersRouter, Lykos, UsersController)]imports
Imports other modules and makes their exported providers available to the importing module.
1export class UsersModule extends DIModule {2 override imports = [DatabaseModule]3}exports
Defines which providers from the current module can be accessed by modules that import it. A token must already be provided by the module or one of its imports.
1export class UsersModule extends DIModule {2 override providers = [UsersService]3 override exports = [UsersService]4}auth
Configures the authentication middleware for a module. UsedefineAuth() to provide the token verifier and the authentication mode.
1override auth = defineAuth({2 verifier: UsersController,3 mode: 'bearer',4})Constructor injection with bind()
Use bind(Class, ...tokens) to describe the dependencies required by a class constructor. The dependency tokens must match the constructor parameter types, count, and order.
1import { DIModule, bind } from 'lykosjs'2 3export class UsersService {4 constructor(5 private readonly database: DatabaseService,6 private readonly logger: LoggerService,7 ) {}8 9 findAll() {10 return this.database.users.findMany()11 }12}13 14export class UsersController {15 constructor(16 private readonly usersService: UsersService,17 ) {}18}19 20export class UsersModule extends DIModule {21 override providers = [22 DatabaseService,23 LoggerService,24 bind(UsersService, DatabaseService, LoggerService),25 ]26 27 override controllers = [28 bind(UsersController, UsersService),29 ]30}LykosJS uses the tokens passed to bind() to resolve constructor arguments before creating the class instance. TypeScript checks the dependency types and their order at compile time.
Registering classes without bind()
A class with no constructor dependencies can be registered directly. The container automatically creates a provider for that class.
1export class LoggerService {2 log(message: string) {3 console.log(message)4 }5}6 7export class AppModule extends DIModule {8 override providers = [LoggerService]9}If a class requires constructor dependencies, usebind() to declare them explicitly.
Value bindings with value()
Use value() when you want to register a class itself as an injectable value instead of creating an instance from it. This is useful for ORM models and other class-based values.
1import { DIModule, value } from 'lykosjs'2import { UserModel } from './models/user.model'3 4export class PersistenceModule extends DIModule {5 override providers = [6 value(UserModel),7 ]8}The class becomes its own injection token. When another class requests UserModel, the container injects theUserModel class itself, not a newly constructed instance.
Module imports and exports
Modules have isolated dependency scopes. A module can access its own providers, providers exported by its imported modules, and providers available from its parent container.
To share a provider with another module, register and export it from the source module, then import that module where the provider is needed.
1import { DIModule } from 'lykosjs'2 3// database.module.ts4export class DatabaseModule extends DIModule {5 override providers = [DatabaseService]6 override exports = [DatabaseService]7}8 9// users.module.ts10export class UsersModule extends DIModule {11 override imports = [DatabaseModule]12 override providers = [bind(UsersService, DatabaseService)]13}In this example, UsersModule can resolveDatabaseService because DatabaseModuleexports it.
Dependency resolution
When the container resolves a token, it follows this lookup order:
11. Existing instance in the current scope.22. Provider registered in the current scope.33. Exported provider from an imported module.44. Parent container.55. ProviderNotFoundError if no provider is found.Once a provider is instantiated, its instance is cached in its container scope. Subsequent resolutions of the same token in that scope return the cached instance.
This means providers are instantiated lazily when first resolved, rather than all being created immediately when registered.
Authentication integration
A module can configure authentication usingdefineAuth(). The verifier property must reference a class registered in the same module scope, typically a controller that implements verifyToken().
1import {2 DIModule,3 defineAuth,4 bind,5} from 'lykosjs'6 7export class UsersController {8 constructor(9 private readonly usersService: UsersService,10 ) {}11 12 async verifyToken(token: string) {13 const user = await this.usersService.verifyToken(token)14 15 if (!user) return null16 17 return {18 id: user.id,19 role: user.role,20 }21 }22}23 24export class UsersModule extends DIModule {25 override providers = [UsersService]26 27 override controllers = [bind(UsersController, UsersService)]28 29 override auth = defineAuth({30 verifier: UsersController,31 mode: 'bearer',32 })33}The verifier class must expose a verifyToken(token)method. It can return a user object or null, either synchronously or asynchronously. The returned user must include a string id property.
During module loading, LykosJS registers an authentication provider that resolves the verifier class from the module container. The authentication middleware then callsverifyToken() for incoming tokens.
The verifier is invoked through an arrow function, preserving the controller instance's this context. This allowsverifyToken() to use injected services.
Authentication options
The defineAuth() configuration supports three authentication modes:
Bearer mode
Reads the token from the Authorization header using the Bearer scheme. No cookie name is required.
1override auth = defineAuth({2 verifier: UsersController,3 mode: 'bearer',4})Cookie mode
Reads the token from the cookie with the configured name. The cookieName property is required.
1override auth = defineAuth({2 verifier: UsersController,3 mode: 'cookie',4 cookieName: 'access_token',5})Both mode
Supports both Bearer tokens and cookies. ThecookieName property is required.
1override auth = defineAuth({2 verifier: UsersController,3 mode: 'both',4 cookieName: 'access_token',5})Complete module example
The following example combines providers, constructor bindings, routers, module exports, and authentication configuration.
1import {2 DIModule,3 bind,4 defineAuth,5} from 'lykosjs'6 7export class UsersModule extends DIModule {8 override providers = [9 DatabaseService,10 bind(UsersService, DatabaseService),11 ]12 13 override controllers = [bind(UsersController, UsersService)]14 15 override routers = [bind(UsersRouter, Lykos, UsersController)]16 17 override exports = [UsersService]18 19 override auth = defineAuth({20 verifier: UsersController,21 mode: 'bearer',22 })23}Common mistakes
Avoid these common configuration mistakes when working with Dependency Injection:
1. Missing provider registration
Every constructor dependency must be registered in the current scope, available through an imported module's exports, or available in the parent container.
1// Incorrect: DatabaseService is not registered.2export class UsersModule extends DIModule {3 override providers = [4 bind(UsersService, DatabaseService),5 ]6}7 8// Correct:9export class UsersModule extends DIModule {10 override providers = [11 DatabaseService,12 bind(UsersService, DatabaseService),13 ]14}2. Incorrect dependency order
The tokens passed to bind() must follow the exact constructor parameter order.
3. Forgetting to export a provider
A provider registered in another module is not automatically available to importing modules. Add its token to the source module's exports array.
4. Registering a class with dependencies directly
Direct class registration is intended for classes with no constructor dependencies. Use bind() when the constructor requires injected dependencies.
5. Using value() for an instance
value() registers the class itself, not an instance created from that class. Use a normal provider orbind() when you need an instantiated class.
6. Incorrect authentication verifier
The class passed to defineAuth() must be registered in the module scope and implement a compatibleverifyToken(token) method. The returned user must contain a string id.
7. Circular dependencies
Avoid dependency chains where a provider eventually depends on itself. LykosJS detects circular dependencies during resolution and reports the dependency chain.
8. Circular module imports
Avoid modules importing each other in a cycle. LykosJS detects circular module imports while loading modules.
DI errors
LykosJS provides specific errors for common dependency injection and module configuration problems. These errors include the relevant class names to help identify the issue.
ProviderNotFoundError
Thrown when the container cannot find a provider for a requested token.
1[LykosJS] No provider found for "DatabaseService".When another provider requires the missing dependency, the error also includes the dependency chain.
1[LykosJS] No provider found for "DatabaseService". Required by: UsersService.CircularDependencyError
Thrown when a provider directly or indirectly depends on itself.
1[LykosJS] Circular dependency detected: UsersService -> OrdersService -> UsersService.DuplicateProviderError
Thrown when the same provider token is registered more than once in the same container scope.
1[LykosJS] Provider "UsersService" is already registered.InvalidExportError
Thrown when a module attempts to export a token that it does not provide and that is not exported by one of its imports.
1[LykosJS] Cannot export "UsersService": it is not provided by this module or its imports.CircularModuleError
Thrown when modules import each other in a circular chain.
1[LykosJS] Circular module import detected: UsersModule -> OrdersModule -> UsersModule.Module not loaded
Calling the module loader's resolve() method for a module that has not been loaded throws a regular Error.
1Module "UsersModule" has not been loaded