Components & Injection

Class Decoration

NoEgo code should make construction explicit. Classes that participate in dependency injection get a component scope, every constructor parameter gets an explicit injection token, and runtime values use parameter tokens. The container handles the rest.

Decorators at a Glance

This snippet shows all three decorator patterns together:

checkout_service.ts
import { Component, Inject, LoadAs, Parameter } from "@noego/ioc";

// A runtime parameter token
export const USER_ID = Parameter.create("userId");

// A swappable contract (abstract class, not interface)
export abstract class PaymentGateway {
  abstract charge(amount: number): Promise<string>;
}

// A concrete service with explicit scope and dependencies
@Component({ scope: LoadAs.Singleton })
export class CheckoutService {
  constructor(
    @Inject(PaymentGateway) private gateway: PaymentGateway,
  ) {}

  async checkout(cart: Cart): Promise<string> {
    return this.gateway.charge(cart.total);
  }
}

Documentation

Core Rules

  • Use @Component on every class the container should manage.
  • Always specify an explicit scope — the decorator default is transient.
  • Always use @Inject(token) — explicit tokens survive circular imports and test setup.
  • Use abstract classes (not interfaces) for injectable contracts.
  • Use Parameter.create() for runtime values that aren't known at startup.
NoEgo

© 2025 NoEgo. All rights reserved.