Skip to main content

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

  1. When modules start, the module system sets an "injection context"
  2. Services are instantiated within this context
  3. inject() looks up services from the DI container
  4. 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 AliasDescription
InjectionTokenToken for identifying services in the container. Can be a class constructor or a symbol for interface tokens.
ServiceClassConstructor type for injectable services. Services must have a parameterless constructor.

Functions

FunctionDescription
createInjectionTokenCreate an injection token for an interface. Use this when you want to inject an interface rather than a concrete class.
injectInject a service dependency.
injectOptionalTry to inject a service, returning undefined if not found.