Manage your application's dependencies with a powerful IoC Container. Support for Singletons, Transients, and Request-scoped services.
Automatically resolves constructor dependencies.
Singleton, Transient, and Request-scoped bindings.
Bind concrete classes to abstract tokens/symbols.
Use @Injectable() to mark classes as dependencies. The container automatically resolves constructor parameters.
1import { Injectable, Inject, container } from "canxjs";23@Injectable()4class ConfigService {5constructor() {6console.log("ConfigService initialized");7}89get(key: string) {10return process.env[key];11}12}1314@Injectable()15class UserService {16constructor(17private config: ConfigService // Auto-wired18) {}1920getUser() {21const dbName = this.config.get("DB_NAME");22// ...23}24}2526// Resolve instance (ConfigService is auto-injected)27const userService = await container.resolve(UserService);
Decouple your code by injecting interfaces (via tokens) instead of concrete classes.
1// Define a token for the interface2const MAIL_PROVIDER = Symbol("MAIL_PROVIDER");34interface MailProvider {5send(to: string, body: string): void;6}78@Injectable()9class SmtpMailer implements MailProvider {10send(to, body) { console.log('Sending via SMTP'); }11}1213@Injectable()14class MockMailer implements MailProvider {15send(to, body) { console.log('Mock email sent'); }16}1718// Bind implementation to token19container.bind(MAIL_PROVIDER, SmtpMailer);2021@Injectable()22class NotificationService {23constructor(24@Inject(MAIL_PROVIDER) private mailer: MailProvider25) {}2627notify() {28this.mailer.send('user@example.com', 'Hello');29}30}
Control the lifecycle of your dependencies.
1import { Injectable, Scope } from "canxjs";23// Singleton (Default) - One instance per application4@Injectable({ scope: Scope.DEFAULT })5class SingletonService {}67// Transient - New instance every time it's resolved8@Injectable({ scope: Scope.TRANSIENT })9class TransientService {}1011// Request - One instance per HTTP request12@Injectable({ scope: Scope.REQUEST })13class RequestContextService {14constructor(@Inject("request") private req: any) {}15}