lib/di
Angular-style dependency injection system.
This module provides a lightweight DI container inspired by Angular's inject() function.
Services can inject dependencies from other modules during construction.
Usage
import { inject } from "@core/di";
import { CharacterService } from "@modules/characters/character.service";
class MyService {
// Inject during construction - the injection context is set by the module system
private characterService = inject(CharacterService);
@Server
async doSomething(ctx: EventContext<[]>) {
// Use the injected service
const character = this.characterService.getActiveCharacter(ctx.source);
}
}
How It Works
- When modules start, the module system sets an "injection context"
- Services are instantiated within this context
inject()looks up services from the DI container- Since modules start in dependency order, dependencies are always available
Important Notes
inject()can only be called during service construction (in field initializers or constructor)- You can only inject services from modules that are dependencies of your module
- Circular dependencies are not supported and will throw an error
Type Aliases
| Type Alias | Description |
|---|---|
| InjectionToken | Token for identifying services in the container. Can be a class constructor or a symbol for interface tokens. |
| ServiceClass | Constructor type for injectable services. Services must have a parameterless constructor. |
Functions
| Function | Description |
|---|---|
| createInjectionToken | Create an injection token for an interface. Use this when you want to inject an interface rather than a concrete class. |
| inject | Inject a service dependency. |
| injectOptional | Try to inject a service, returning undefined if not found. |