﻿<div align="center">

# @run-js/dependency-injection-core

[![npm version](https://img.shields.io/npm/v/@run-js/dependency-injection-core)](https://www.npmjs.com/package/@run-js/dependency-injection-core)&nbsp;
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-blue.svg)](https://www.typescriptlang.org/)&nbsp;
[![Zero Dependencies](https://img.shields.io/badge/no%20dependencies-%E2%9C%94-green.svg)](#)&nbsp;
[![No AI](https://img.shields.io/badge/code-no%20AI%20generated%20vibe%20code%20%3A%29-d946ef)](#)&nbsp;
[![Test Coverage](https://img.shields.io/badge/test%20coverage-100%25-brightgreen)](#)&nbsp;
[![License](https://img.shields.io/badge/license-EULA-blue.svg)](https://dependency-injection-core.run-js.com/#/license)

*The fastest lightweight Dependency Injection container for TypeScript and JavaScript*

Enjoying the library? 😊 Help us keep it fast, reliable, and well maintained. [Buy a Premium license](https://store.run-js.com/dependency-injection-core).

[🏠 Homepage](http://dependency-injection-core.run-js.com) • [🚀 Quick Start](#-quick-start)

</div>

## 📋 Table of Contents

- [✨ Features](#-features)
- [📊 Comparison with Other DI Containers](#-comparison-with-other-di-containers)
- [📦 Installation](#-installation)
  - [🔧 Package Compatibility](#-package-compatibility)
- [🚀 Quick Start](#-quick-start)
- [🏷️ Naming & Service Types](#️-naming--service-types)
- [🏗️ Container Setup](#️-container-setup)
  - [Using the Static Instance (Recommended)](#using-the-static-instance-recommended)
  - [Separate Container Instance](#separate-container-instance)
  - [Self-Registering Decorators](#self-registering-decorators)
- [📚 Basic Examples](#-basic-examples)
  - [Class Binding](#class-binding-default-as-non-singleton)
  - [Singleton Binding](#binding-a-class-as-singleton)
  - [Instance Binding](#binding-a-specific-instance)
  - [Custom Service Types](#binding-a-class-with-custom-servicetype)
  - [Named Specifications](#binding-a-class-with-a-specification)
  - [Factory Methods](#binding-a-factory-function)
  - [🆕 Async Factories and Async Resolution](#-async-factories-and-async-resolution-added-2026-10-12)
  - [Advanced Examples 🔒 Premium](#combined-extended-example-with-decorators--premium)
- [🎨 Decorators](#-decorators)
  - [@bind Class Decorator](#bind-class-decorator)
  - [@bindSingleton Decorator](#bindsingleton-decorator)
  - [@resolve Property Decorator](#resolve-property-decorator)
  - [@resolveAll Property Decorator](#resolveall-property-decorator)
  - [🆕 Async Property Decorators](#-async-property-decorators-added-2026-10-12)
- [🔨 Constructor Resolution](#-constructor-resolution)
  - [Automatic Resolution](#automatic-resolution)
  - [Explicit Resolution with @resolveParameter](#explicit-resolution-with-resolveparameter)
  - [Resolving Multiple Services with @resolveAllParameter](#resolving-multiple-services-with-resolveallparameter)
  - [🆕 Optional Resolution with ResolveMode](#-optional-resolution-with-resolvemode-added-2026-09-09)
  - [⚠️ Minification Warning](#️-minification-warning)
- [🛠️ Advanced Features](#️-advanced-features)
  - [Container Cloning](#container-cloning)
  - [Self Binding](#di-container-self-binding)
  - [🧪 Testing](#-testing)
  - [Disposal & Cleanup 🔒 Premium](#disposal--cleanup--premium)
- [⚡ Performance](#-performance)
  - [Scaling Test (O(1) Verification)](#scaling-test-o1-verification)
  - [Competitor Benchmark](#competitor-benchmark)
- [⚙️ Configuration Options](#️-configuration-options)
- [💎 Premium Features](#-premium-features)
- [🐛 Troubleshooting](#-troubleshooting)
- [🔧 Requirements](#-requirements)
- [📄 License Information](#-license-information)
- [🌐 About Rudolf Run Ltd](#-about-rudolf-run-ltd)
- [🏷️ Keywords](#️-keywords)

## ✨ Features

- 🎯 **Zero Dependencies** - Lightweight and self-contained
- ⚡ **Fastest DI Container** - [Outperforms](#competitor-benchmark) tsyringe, InversifyJS, Awilix, and TypeDI
- 📦 **Dual Package Support** - Works in both ESM and CommonJS environments (Node.js, Jest, Vite, modern bundlers)
- 🔒 **100% Test Coverage** - Quality you can trust
- ⚡ **Performance Tested** - Map-indexed lookups, tested with 1M bindings
- 🎨 **Flexible API** - Declarative binding, decorators, or both
- 🏗️ **Constructor Injection** - Full dependency resolution
- ⚡ **Property Injection** - Lazy loading with circular dependency support
- 🏭 **Factory Patterns** - Custom instance creation
- 🔌 **Interception** - Post-process resolved services (`postProcessor`, `resolveAllInterceptor` 🔒 Premium)
- 📦 **Singletons & Transients** - Flexible instance management
- 🧪 **Unit Test Support** - Built for testability
- 🔄 **Container Cloning** - Multiple container instances

## 📊 Comparison with Other DI Containers

| Feature | @run-js/di | InversifyJS | tsyringe | TypeDI | Awilix |
|---|:---:|:---:|:---:|:---:|:---:|
| **Version** | 2.1.1 | 8.2.3 | 4.10.0 | 0.10.0 | 13.0.5 |
| **Last Update[⁵](#comparison-note-5)** | **Nov 2026** | Jul 2026 | Apr 2025 | ⚠️ Jan 2021 | **Jun 2026** |
| **Open Issues[⁵](#comparison-note-5)** | **0** | 12 | 82 | 59 | 5 |
| **Tarball Size** | ~46.9 kB | ~9.5 kB | ~27.2 kB | ~66.1 kB | ~80.3 kB |
| **Install Size (with deps / code only[³](#comparison-note-3))** | **~181 kB / ~36.0 kB** | ~1.32 MB / ~391 kB | ~423 kB / ~114 kB | ~675 kB / ~95.9 kB | ~842 kB / ~258 kB |
| **[Performance](#-performance) [⁴](#comparison-note-4) Bind/Resolve** | **~1.81 / ~5.22 ms** 🥇 | ~24.89 / ~20.82 ms | ~4.20 / ~16.28 ms | ~271.80 / ~1,312.47 ms | ~13.04 / ~14.51 ms |
| **Ships Source Maps** | ❌ | ✅ | ❌ | ✅ | ✅ |
| **Dependencies** | **0** | 3 | 1 | **0** | 1 |
| **Requires reflect-metadata** | **No** | Yes | Yes | Yes | **No** |
| **100% Test Coverage** | **Yes** | No | No | No | ~Yes |
| **Constructor Injection** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Property Injection** | ✅ Lazy | ❌ | ❌ | ✅ | ❌ |
| **Auto Constructor Resolution** | ✅ | ❌ | ❌ | ✅[¹](#comparison-note-1) | ✅[¹](#comparison-note-1) |
| **Decorator Registration** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **Factory Binding** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Singleton Support** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Scoped Lifetime** | ❌ | ✅ | ✅ | ❌ | ✅ |
| **Named/Tagged Bindings** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **Resolve All (multi)** | ✅ | ✅ | ✅ | ❌ | ❌ |
| **Interface Mode (auto I-prefix)** | ✅ Premium | ❌ | ❌ | ❌ | ❌ |
| **Case-Insensitive Resolution** | ✅ Premium | ❌ | ❌ | ❌ | ❌ |
| **Circular Dependency Detection** | ✅ | ✅ | ✅[²](#comparison-note-2) | ❌ | ❌ |
| **Container Hierarchy/Scopes** | ❌ | ✅ | ✅ | ✅ | ✅ |
| **Async Resolution** | ✅ | ✅ | ❌ | ❌ | ❌ |
| **Disposal/Cleanup** | ✅ Premium | ✅ | ✅ | ❌ | ✅ |
| **Auto-loading Modules** | ❌ | ❌ | ❌ | ❌ | ✅ |
| **Browser Support** | ✅ | ✅ | ✅ | ✅ | ✅ |

<a id="comparison-note-1"></a><sub>¹TypeDI and Awilix auto-resolution relies on `reflect-metadata` or parameter name parsing respectively - both break with minification.</sub><br>
<a id="comparison-note-2"></a><sub>²tsyringe requires the `delay()` helper for circular dependencies.</sub><br>
<a id="comparison-note-3"></a><sub>³Code only is the JavaScript loaded by `require()` in one module format, with dependencies. Both sizes include `reflect-metadata` where required.</sub><br>
<a id="comparison-note-4"></a><sub>⁴Bind 10k instances / Resolve 50k calls (ms). Every library measured in its own standalone Node.js process - see [Performance](#-performance) for full results.</sub><br>
<a id="comparison-note-5"></a><sub>⁵Version and Last Update are the latest npm release. Open Issues are the GitHub repository counts, checked Oct 12, 2026. Tarball Size is the compressed npm tarball; Install Size is based on [Packagephobia](https://packagephobia.com/).</sub>

## 📦 Installation
```bash
npm install @run-js/dependency-injection-core
```

> 🤖 **AI coding assistants:** the package ships an `llms.txt` with the rules and the API in compact form. Point your assistant to `node_modules/@run-js/dependency-injection-core/llms.txt` so it generates correct bindings and service types.

### 🔧 Package Compatibility

This package supports both **CommonJS** and **ESM** environments through dual package exports:

- 🚀 **ESM (Modern)**: Works with Vite, modern bundlers, and `import` statements
- 🏗️ **CommonJS (Legacy)**: Compatible with Node.js, Jest, and `require()` statements
- 📦 **Automatic Detection**: The correct format is selected automatically based on your environment

**Usage Examples:**
```typescript
// ESM (import) - for modern bundlers, Vite, etc.
import { DependencyInjectionContainer, bind, resolve } from '@run-js/dependency-injection-core';

// CommonJS (require) - for Node.js, Jest, etc.
const { DependencyInjectionContainer, bind, resolve } = require('@run-js/dependency-injection-core');
```

Both approaches provide identical functionality and TypeScript support.

## 🚀 Quick Start

> ⚠️ Decorators need `"experimentalDecorators": true` in `tsconfig.json`. With `target` ES2022 or newer, also set `"useDefineForClassFields": false`, or `@resolve` properties stay `undefined`. See [Decorators Not Working](#decorators-not-working).

```typescript
import { DependencyInjectionContainer, bind, resolve } from '@run-js/dependency-injection-core';

// Register a service - @bind() uses the class name 'UserService' as service type
@bind()
class UserService {
  getUsers() { return ['Alice', 'Bob']; }
}

// Consume it through a lazy property - resolved on first access, no constructor needed
@bind()
class AppService {
  @resolve('UserService') private userService: UserService;

  run() {
    return this.userService.getUsers();
  }
}

const app = DependencyInjectionContainer.instance.resolve(AppService);
console.log(app.run()); // ['Alice', 'Bob']
```

**Prefer lazy properties over constructor injection.** They need less code, work in classes the container did not create, and never hit cyclic-dependency problems because nothing resolves until the property is read. Use [constructor injection](#-constructor-resolution) only when a class must not be constructible without its dependencies.

Without decorators, the same setup with the fluent API:

```typescript
const container = DependencyInjectionContainer.instance;
container.setup()
  .bind(UserService)
  .bind(AppService);
```

## 🏷️ Naming & Service Types

Every binding is stored under a **service type** - a plain string. Resolution looks that string up.

| Where | Service type used | Explicit override |
|---|---|---|
| `@bind()` / `bind(Class)` | class name (`UserService`) | `@bind('IUserService')` / `bind(Class, 'IUserService')` |
| `@resolve()` property | property name (`userService`) | `@resolve('IUserService')` |
| `@resolveParameter()` / auto constructor | parameter name (`userService`) | `@resolveParameter('IUserService')` |

**Standard (no license):** matching is exact and case-sensitive. Pass the service type explicitly wherever the name differs from the class name - in practice, on every `@resolve` and `@resolveParameter`.

**Premium:** `caseSensitive` is `false` and `interfaceMode` is `true` by default. Then the convention is: **property / parameter name = interface name without the leading `I`, in camelCase**. `storageService` matches `StorageService` and `IStorageService`; `@resolve()` with no argument is enough.

When the class name is not the name you resolve by - a `SqlUserRepository` that fulfils `IUserRepository` - bind it under the interface name and resolve by that name. This is what makes swapping implementations (or [faking them in tests](#-testing)) possible:

```typescript
interface IUserRepository { find(id: number): User; }

@bind('IUserRepository')
class SqlUserRepository implements IUserRepository {
  find(id: number) { /* SQL */ }
}

class UserService {
  @resolve('IUserRepository') repository: IUserRepository;   // Standard
  // @resolve() userRepository: IUserRepository;             // Premium: 'userRepository' matches 'IUserRepository'
}
```

The service type is a plain string, so it is the only thing that must match. `UserService` never imports `SqlUserRepository`.

**Symbols:** a `symbol` works as service type as well. It matches only itself - `caseSensitive`, `interfaceMode` and `pluralMode` apply to strings only.

```typescript
interface ILogger { log(message: string): void; }
const loggerToken: unique symbol = Symbol('Logger');

@bind(loggerToken)
class ConsoleLogger implements ILogger {
  log(message: string) { console.log(message); }
}

class UserService {
  @resolve(loggerToken) logger: ILogger;
}
```

## 🏗️ Container Setup

This package provides a **static instance** for convenience, but you can also create separate containers for advanced scenarios.

> 💡 **Tip**: Decorators register with the static instance: `@bind` / `@bindSingleton` add their bindings when the module is imported, and `@resolveParameter` / `@resolveAllParameter` store their parameter settings there. A [clone](#container-cloning) copies all of these, so decorated classes imported before `clone()` also resolve from the clone. `@resolve` / `@resolveAll` **properties** always resolve from the static instance.

> 💡 **Order does not matter**: `@bind` registers at import; `@resolve` properties resolve on first access. `setLicense()`, options, and fluent bindings only need to run before the first resolve - not before your decorated classes are imported.

### Using the Static Instance (Recommended)

```typescript
import { DependencyInjectionContainer } from '@run-js/dependency-injection-core';

const container = DependencyInjectionContainer.instance;

// Fluent configuration
class ServiceA { }
container.setup().bind(ServiceA);
const serviceA = container.resolve(ServiceA);
```

### Separate Container Instance

```typescript
// Copy of the static instance: all bindings made so far (decorators and fluent API) and parameter decorator settings
const copy = DependencyInjectionContainer.instance.clone();

// Or an empty container with default options
import { DependencyInjectionContainerInternal } from '@run-js/dependency-injection-core';
const empty = new DependencyInjectionContainerInternal();
empty.setup().bind(ServiceA);
```

An empty container has no `@bind` registrations, no self binding, and does not know the `@resolveParameter` / `@resolveAllParameter` settings - constructor parameters are matched by name only. Bindings added to the static instance after `clone()` are not copied. The static instance can not be replaced. See [Container Cloning](#container-cloning).

### Self-Registering Decorators

```typescript
import { bind, bindSingleton } from '@run-js/dependency-injection-core';

@bind()
class ServiceB { }

@bindSingleton()
class ServiceC { }

const serviceB = container.resolve(ServiceB);
const serviceC = container.resolve(ServiceC);
```

For container configuration options, see [Configuration Options](#️-configuration-options).

## 📚 Basic Examples

### Class Binding (default as non-singleton)

```typescript
class ServiceA { }
const container = DependencyInjectionContainer.instance;

// Declare a binding
container.setup().bind(ServiceA);

// Each resolve() creates a new instance
const service1 = container.resolve(ServiceA);
const service2 = container.resolve(ServiceA);
console.log(service1 === service2); // false
```

### Interface Mode & Case Sensitivity 🔒 Premium

With a Premium license, **interface mode** and **case-insensitive** matching are on by default.

```typescript
interface IServiceA { }
class ServiceA implements IServiceA { }

container.setup().bind(ServiceA);

// Works with leading 'I' (interface mode)
let service: IServiceA = container.resolve('IServiceA');
console.log(service instanceof ServiceA); // true

// Works with case-insensitive matching
service = container.resolve('iservicea');
console.log(service instanceof ServiceA); // true
```

> 🔧 Both features can be disabled via [container options](#️-configuration-options).

### Binding a Class as Singleton

```typescript
class ServiceA { }
const container = DependencyInjectionContainer.instance;

// Declare a singleton binding
container.setup().bind(ServiceA).asSingleton();

// Same instance returned every time
const service1 = container.resolve(ServiceA);
const service2 = container.resolve(ServiceA);
console.log(service1 === service2); // true
```

### Binding a Specific Instance

```typescript
class ServiceA {
  constructor(public config: string) {}
}

// Pre-configured instance
const specificInstance = new ServiceA('production-config');

// Bind to specific instance (automatically singleton)
DependencyInjectionContainer.instance.setup().bind(ServiceA).toInstance(specificInstance);

const service = DependencyInjectionContainer.instance.resolve(ServiceA);
console.log(service === specificInstance); // true
console.log(service.config); // 'production-config'
```

### Binding a Class with Custom ServiceType

```typescript
class DatabaseService { }
const container = DependencyInjectionContainer.instance;

// Map custom name to class
container.setup().bind('database').toClass(DatabaseService);

const service = container.resolve('database');
console.log(service instanceof DatabaseService); // true
```

### Binding a Class with a Specification

Specifications allow multiple implementations of the same interface:

```typescript
interface IAuthService { }

class AuthServiceJwt implements IAuthService { }
class AuthServiceApiKey implements IAuthService { }

const container = DependencyInjectionContainer.instance;

// Register multiple implementations with specifications
container.setup()
  .bind(AuthServiceJwt).withServiceType('IAuthService').withSpecification('JWT')
  .bind(AuthServiceApiKey).withServiceType('IAuthService').withSpecification('ApiKey');

// Resolve specific implementation
const jwtAuth = container.resolve('IAuthService', 'JWT');
const apiKeyAuth = container.resolve('IAuthService', 'ApiKey');

console.log(jwtAuth instanceof AuthServiceJwt); // true
console.log(apiKeyAuth instanceof AuthServiceApiKey); // true
```

### Binding a Factory Function

For custom instance creation logic:

```typescript
class DatabaseService {
  constructor(public connectionString: string) {}
}

const container = DependencyInjectionContainer.instance;

// Custom factory with configuration
container.setup()
  .bind(DatabaseService)
  .toFactory(() => {
    const config = process.env.NODE_ENV === 'production'
      ? 'prod-connection'
      : 'dev-connection';
    return new DatabaseService(config);
  });

const service = container.resolve(DatabaseService);
```

### 🆕 Async Factories and Async Resolution (Added 2026-10-12)

Register an async factory with `toAsyncFactory()` and resolve it with `resolveAsync()` or `resolveAllAsync()`. Async factories are awaited through the complete dependency graph, also for constructor parameters:

```typescript
class Repository {
  constructor(public database: Database) {}
}

const container = DependencyInjectionContainer.instance;

container.setup()
  .bindSingleton('database').toAsyncFactory(async () => connect(process.env.DATABASE_URL))
  .bind(Repository);

const repository = await container.resolveAsync<Repository>(Repository);
const databases = await container.resolveAllAsync<Database>('database');
```

- `resolve()` / `resolveAll()` throw for a binding with an async factory. An async singleton that was already created by `resolveAsync()` is returned by `resolve()` as well.
- Concurrent `resolveAsync()` calls for an async singleton share one factory call. A rejected factory is called again on the next resolve.
- Bindings without an async factory in their graph are created synchronously inside `resolveAsync()`.

### Combined Extended Example with Decorators 🔒 Premium

With a Premium license the container matches everything by convention - no service type strings, no parameter decorators. This example uses interface mode, case-insensitive matching, plural mode, and automatic constructor resolution together:

```typescript
await DependencyInjectionContainer.instance.setLicense('your-license-key');

interface IDataService { dbConnectionString: string; }
interface IAuthService { name: string; }
interface IPlugin { }

@bindSingleton()
class DataService implements IDataService {
  constructor(@resolve('sqlConnection') public dbConnectionString: string) { }
}

@bind('IAuthService', 'JWT')
class AuthServiceJwt implements IAuthService { name = 'jwt'; }

@bindSingleton('IAuthService', 'ApiKey')
class AuthServiceApiKey implements IAuthService {
  name = 'apiKey';
  // Undecorated parameter: 'dataService' is found and injected as DataService
  constructor(public dataService: IDataService) { }
}

@bind('IPlugin') class AuditPlugin implements IPlugin { }
@bind('IPlugin') class MetricsPlugin implements IPlugin { }

class App {
  @resolveAll() authServices: IAuthService[];             // 'authServices' -> all 'IAuthService' (plural + interface mode)
  @resolveAll() plugins: IPlugin[];                       // 'plugins' -> all 'IPlugin'
  @resolve() dataService: IDataService;                   // 'dataService' -> 'DataService' (interface mode, case-insensitive)
  @resolve(undefined, 'ApiKey') authService: AuthServiceApiKey; // specification only, type from property name
}

DependencyInjectionContainer.instance.setup()
  .bind('sqlConnection').toInstance('Server=localhost;Database=MyApp;');

const app = new App(); // Not created by the container - lazy properties still work
console.log(app.authServices.map(a => a.name));           // ['jwt', 'apiKey']
console.log(app.plugins.length);                          // 2
console.log(app.dataService.dbConnectionString);          // 'Server=localhost;Database=MyApp;'
console.log(app.authService.dataService === app.dataService); // true - singleton
console.log(app.authServices[1] === app.authService);     // true - singleton
```

### Fluent Configuration

Chain multiple bindings for clean, readable setup:

```typescript
interface IDataService { dbConnectionString: string; }
class DataService implements IDataService {
  constructor(public dbConnectionString: string) { }
}

interface IAuthService { }
class AuthServiceJwt implements IAuthService { }
class AuthServiceApiKey implements IAuthService {
  constructor(public dataService: IDataService) { }
}

const container = DependencyInjectionContainer.instance;

// Comprehensive fluent configuration
container.setup()
  .bind('dbConnectionString', 'sql')
    .toFactory(() => process.env.DB_CONNECTION || 'localhost')
  .bind(DataService)
    .addConstructionParameter('dbConnectionString', 'dbConnectionString', 'sql')
  .bind(AuthServiceJwt, 'IAuthService', 'JWT')
  .bindSingleton(AuthServiceApiKey, 'IAuthService', 'ApiKey')
    .addConstructionParameter('dataService', DataService)
  .bindSingleton(AuthServiceApiKey, 'someOtherServiceName')
    .addConstructionParameter('dataService', DataService);

// Use the configured services
const authServices: IAuthService[] = container.resolveAll('IAuthService');
console.log(authServices.length); // 2

const apiKeyService: AuthServiceApiKey = container.resolve('IAuthService', 'ApiKey');
console.log(apiKeyService.dataService instanceof DataService); // true
```

## 🎨 Decorators

Decorators provide a clean, declarative way to configure dependency injection. They work on classes, properties, and constructor parameters.

> ⚠️ **Requirements**: Enable `experimentalDecorators` in your TypeScript configuration.

### @bind Class Decorator

Automatically registers classes when the module is loaded. Perfect for self-contained services.

#### Basic Class Registration

```typescript
// Automatically registers when file is imported
@bind()
class ServiceA {
}

const service = DependencyInjectionContainer.instance.resolve(ServiceA);
console.log(service instanceof ServiceA); // true
```

#### Custom Service Type

```typescript
@bind('myCustomName')
class ServiceB { }

const service = DependencyInjectionContainer.instance.resolve('myCustomName');
console.log(service instanceof ServiceB); // true
```

#### With Specifications

```typescript
@bind('AuthService', 'JWT')
class JwtAuthService { }

const service = container.resolve('AuthService', 'JWT');
console.log(service instanceof JwtAuthService); // true
```

#### With Lazy Property Injection

```typescript
@bind()
class ServiceA { }

@bind()
class ServiceB {
  @resolve('ServiceA') public serviceA: ServiceA;
}

const serviceB = container.resolve(ServiceB);
console.log(serviceB.serviceA instanceof ServiceA); // true
```

Constructor injection is also supported - see [🔨 Constructor Resolution](#-constructor-resolution).

### @bindSingleton Decorator

Same as `@bind` but registers the class as a **singleton**.

```typescript
@bindSingleton()
class ConfigService {
  private config = { apiUrl: 'https://api.example.com' };

  getConfig() { return this.config; }
}

const config1 = container.resolve(ConfigService);
const config2 = container.resolve(ConfigService);
console.log(config1 === config2); // true - same instance
```

### @resolve Property Decorator

Creates **lazy-loading properties** that resolve dependencies on first access. Works in any class, even those not created via the container. This is the recommended way to inject dependencies.

#### Explicit Service Type

```typescript
interface IServiceB { someMethod(): string; }
class ServiceB implements IServiceB { someMethod() { return 'ok'; } }

class ServiceA {
  @resolve('IServiceB') serviceB: IServiceB;

  useService() {
    // Resolved on first access, cached afterwards
    return this.serviceB.someMethod();
  }
}

DependencyInjectionContainer.instance.setup().bind(ServiceB, 'IServiceB');
const service = new ServiceA(); // Can be created anywhere
console.log(service.serviceB instanceof ServiceB); // true
```

#### Automatic Service Type 🔒 Premium

With a Premium license, the property name is the service type: `serviceB` matches `ServiceB` and `IServiceB`.

```typescript
class ServiceA {
  @resolve() serviceB: IServiceB;
}
```

#### Cyclic Dependencies

Lazy properties resolve on first access, not at construction. A cycle across files - `ServiceA` needs `ServiceB`, `ServiceB` needs `ServiceC`, `ServiceC` needs `ServiceA` - works without any workaround. The service type is a string, so each file only needs a type-only import:

```typescript
// serviceA.ts
import type { ServiceB } from './serviceB';

@bind()
export class ServiceA {
  @resolve('ServiceB') serviceB: ServiceB;
  name() { return 'A'; }
  chain() { return this.name() + this.serviceB.chain(); }
}

// serviceB.ts
import type { ServiceC } from './serviceC';

@bind()
export class ServiceB {
  @resolve('ServiceC') serviceC: ServiceC;
  name() { return 'B'; }
  chain() { return this.name() + this.serviceC.chain(); }
}

// serviceC.ts
import type { ServiceA } from './serviceA';

@bind()
export class ServiceC {
  @resolve('ServiceA') serviceA: ServiceA;
  name() { return 'C'; }
  chain() { return this.name() + this.serviceA.name(); }
}

// main.ts
const a = DependencyInjectionContainer.instance.resolve(ServiceA);
console.log(a.chain()); // 'ABCA'
```

The same cycle with constructor injection throws `Cyclic dependency detected`.

#### With Specifications

```typescript
interface IDatabaseService { }
@bind('IDatabaseService', 'MySQL')
class MySqlService implements IDatabaseService { }
@bind('IDatabaseService', 'Oracle')
class OracleSqlService implements IDatabaseService { }

class AppService {
  @resolve('IDatabaseService', 'MySQL') db: IDatabaseService;
}
```

### @resolveAll Property Decorator

Creates **lazy-loading properties** that resolve **all registered instances** of a service type on first access.

#### Automatic Plural Matching 🔒 Premium

Relies on Premium defaults (`pluralMode`, `interfaceMode`, case-insensitive):

```typescript
interface IMyService { }
class ServiceB implements IMyService { }
class ServiceC implements IMyService { }

class ServiceA {
  // Automatically matches 'myServices' to 'IMyService' (plural mode)
  // Also supports interface mode: removes/adds 'I' prefix
  @resolveAll() myServices: IMyService[];

  getAllData() {
    // All registered services resolved on first access
    return this.myServices.map(service => service.getData());
  }
}

DependencyInjectionContainer.instance.setup()
  .bind('ServiceA').toClass(ServiceA)
  .bind('IMyService').toClass(ServiceB)
  .bind('IMyService').toClass(ServiceC);

const service = DependencyInjectionContainer.instance.resolve('ServiceA');
console.log(service.myServices.length); // 2
console.log(service.myServices[0] instanceof ServiceB); // true
console.log(service.myServices[1] instanceof ServiceC); // true
```

> 💡 **Plural Mode**: Property names ending in 's' automatically match singular service types. Can be disabled via [container options](#️-configuration-options).

#### Custom Service Type

```typescript
interface IMyService { }
@bind('MyService')
class ServiceB implements IMyService { }
@bind('MyService')
class ServiceC implements IMyService { }

@bind()
class ServiceA {
  @resolveAll('MyService') services: IMyService[];
}

const service = DependencyInjectionContainer.instance.resolve(ServiceA);
console.log(service.services.length); // 2
console.log(service.services[0] instanceof ServiceB); // true
console.log(service.services[1] instanceof ServiceC); // true
```

#### With Specifications

```typescript
interface IPlugin { }
@bind('Plugin', 'Logging')
class ConsoleLoggingPlugin implements IPlugin { }
@bind('Plugin', 'Logging')
class AwsLoggingPlugin implements IPlugin { }
@bind('Plugin', 'Caching')
class AwsCachingPlugin implements IPlugin { }

class AppService {
  @resolveAll('Plugin', 'Logging') logger: IPlugin[];
}

const service = DependencyInjectionContainer.instance.resolve(AppService);
console.log(service.logger.length); // 2
console.log(service.logger[0] instanceof ConsoleLoggingPlugin); // true
console.log(service.logger[1] instanceof AwsLoggingPlugin); // true
```

### 🆕 Async Property Decorators (Added 2026-10-12)

`@resolvePropertyAsync` and `@resolveAllPropertyAsync` create lazy-loading properties of type `Promise<T>` / `Promise<T[]>` that resolve via `resolveAsync()` / `resolveAllAsync()` on first access. The promise is cached; a rejected resolve is retried on the next access. Parameters are the same as for `@resolveProperty` / `@resolveAllProperty`, including `ResolveMode`.

```typescript
class ReportService {
  @resolvePropertyAsync() database: Promise<Database>;
  @resolveAllPropertyAsync('Plugin') plugins: Promise<IPlugin[]>;

  async createReport() {
    const database = await this.database;
    return database.query('SELECT 1');
  }
}
```

## 🔨 Constructor Resolution

When the container creates instances, it automatically resolves constructor parameters to inject dependencies.

### Automatic Resolution

If constructor parameter names match a registered service type, dependencies are resolved automatically - no decorators required. Matching is exact and case-sensitive in Standard; the example below relies on Premium (`userService` matching `UserService`):

```typescript
@bind()
class LoggingService { }

@bind()
class CacheService { }

@bind()
class ProductService {
  constructor(public loggingService: LoggingService, public cacheService: CacheService) { }
}

const productService = container.resolve(ProductService);
console.log(productService.loggingService instanceof LoggingService); // true
console.log(productService.cacheService instanceof CacheService); // true
```

With Premium, parameter names are matched using **interface mode** and **case-insensitive** matching - so `loggingService` matches `LoggingService`, `ILoggingService`, etc. Without it, use `@resolveParameter('LoggingService')`.

### Explicit Resolution with @resolveParameter

When parameter names don't match the service type, use the `@resolveParameter` decorator to explicitly specify what to resolve:

```typescript
@bind()
class AppService {
  constructor(
    @resolveParameter('sqlConnection') public dbConnectionString: string,
    @resolveParameter('cacheTimeout') public timeout: number
  ) { }
}

const container = DependencyInjectionContainer.instance;
container.setup()
  .bind('sqlConnection').toInstance('Server=localhost;Database=MyApp;')
  .bind('cacheTimeout').toInstance(3000);

const service = container.resolve(AppService);
console.log(service.dbConnectionString); // 'Server=localhost;Database=MyApp;'
console.log(service.timeout); // 3000
```

#### With Specifications

```typescript
interface IDatabaseService { }

@bind('IDatabaseService', 'MySQL')
class MySqlService implements IDatabaseService { }

@bind('IDatabaseService', 'SQLServer')
class SqlServerService implements IDatabaseService { }

@bind()
class OrderService {
  constructor(@resolveParameter('IDatabaseService', 'MySQL') public db: IDatabaseService) { }
}

@bind()
class ReportService {
  constructor(@resolveParameter('IDatabaseService', 'SQLServer') public db: IDatabaseService) { }
}

const orderService = container.resolve(OrderService);
console.log(orderService.db instanceof MySqlService); // true

const reportService = container.resolve(ReportService);
console.log(reportService.db instanceof SqlServerService); // true
```

### Resolving Multiple Services with @resolveAllParameter

Use `@resolveAllParameter` to inject all registered instances of a service type:

```typescript
interface IPlugin { name: string; }

@bind('IPlugin')
class AuthPlugin implements IPlugin { name = 'auth'; }

@bind('IPlugin')
class LogPlugin implements IPlugin { name = 'log'; }

@bind()
class PluginManager {
  constructor(@resolveAllParameter('IPlugin') public plugins: IPlugin[]) { }
}

const manager = container.resolve(PluginManager);
console.log(manager.plugins.length); // 2
```

#### With Specifications

```typescript
interface IPlugin { }

@bind('IPlugin', 'Logging')
class ConsoleLoggingPlugin implements IPlugin { }

@bind('IPlugin', 'Logging')
class AwsLoggingPlugin implements IPlugin { }

@bind('IPlugin', 'Caching')
class AwsCachingPlugin implements IPlugin { }

@bind()
class LoggingService {
  constructor(@resolveAllParameter('IPlugin', 'Logging') public loggers: IPlugin[]) { }
}

const service = container.resolve(LoggingService);
console.log(service.loggers.length); // 2
console.log(service.loggers[0] instanceof ConsoleLoggingPlugin); // true
console.log(service.loggers[1] instanceof AwsLoggingPlugin); // true
```

### 🆕 Optional Resolution with ResolveMode (Added 2026-09-09)

By default, `@resolve`, `@resolveAll`, `@resolveParameter`, `@resolveAllParameter`, `@resolveProperty`, and `@resolveAllProperty` throw an error when no matching binding is found - unless the container's [`throwIfNotFound`](#-throw-if-not-found) option is set to `false`. Pass `ResolveMode.Required` or `ResolveMode.Optional` to override that per-decorator, regardless of the container option:

```typescript
import { ResolveMode } from '@run-js/dependency-injection-core';

@bind()
class AppService {
  constructor(
    // Optional constructor parameter - undefined if 'FeatureFlags' is not bound, regardless of throwIfNotFound
    @resolveParameter('FeatureFlags', undefined, ResolveMode.Optional) public featureFlags: FeatureFlags | undefined,
    // Optional multi-resolution - [] if no 'IPlugin' bindings exist, regardless of throwIfNotFound
    @resolveAllParameter('IPlugin', undefined, ResolveMode.Optional) public plugins: IPlugin[]
  ) { }
}

class ReportService {
  // Optional lazy property - undefined if 'Logger' is not bound, regardless of throwIfNotFound
  @resolveProperty('Logger', undefined, undefined, ResolveMode.Optional) logger: Logger | undefined;
}
```

- `ResolveMode.Default` (the default when omitted) - defers to the container's `throwIfNotFound` option: throws when it's `true` (the container default), resolves to `undefined`/`[]` when it's `false`.
- `ResolveMode.Required` - always throws when no matching binding is found, even if `throwIfNotFound` is `false`.
- `ResolveMode.Optional` - always resolves to `undefined` (single) or `[]` (multi) instead of throwing, even if `throwIfNotFound` is `true`.

The `resolve()` / `resolveAll()` alias decorators accept `ResolveMode` as their third parameter and forward it to the underlying parameter or property decorator.

### ⚠️ Minification Warning

> **⚠️ Important**: Code minifiers and uglifiers (such as Terser, UglifyJS, or esbuild with minification) can **rename class names, parameter names, and property names** to short identifiers - which will silently break service resolution.

**Affected**: **All** decorators without an explicit `serviceType` argument are affected:
- `@bind()` / `@bindSingleton()` - fall back to the class name
- `@resolve()` / `@resolveAll()` - fall back to the property name
- `@resolveParameter()` / `@resolveAllParameter()` - fall back to the parsed parameter name
- Automatic constructor resolution - relies on parsed parameter names

**Not affected**: Decorators with an explicit service type (e.g. `@bind('MyService')`, `@resolve('MyService')`, `@resolveParameter('MyService')`), `toInstance`, and `toFactory` bindings. If your bundler keeps class, function, and property names (see below), nothing in this section applies to you.

**Solutions**:

1. **Configure your bundler to preserve names**:

   | Bundler | Option |
   |---|---|
   | **Terser** | `keep_classnames: true, keep_fnames: true` |
   | **esbuild** | `--keep-names` |
   | **UglifyJS** | `keep_fnames: true` |
   | **Webpack** (with Terser) | `optimization.minimizer` → TerserPlugin with above options |
   | **Rollup** (with Terser) | `terser({ keep_classnames: true, keep_fnames: true })` |
   | **SWC** | `jsc.minify.keepClassnames: true, jsc.minify.keepFnames: true` |

2. **Disable minification for server-side code** - if you're running Node.js server-side, minification typically isn't needed.

3. **Pass an explicit service type** to all decorators:
   ```typescript
   @bind('ServiceA')
   class ServiceA { }

   @bind('ServiceD')
   class ServiceD {
     constructor(
       @resolveParameter('ServiceA') public serviceA: ServiceA,
       @resolveParameter('ServiceB') public serviceB: ServiceB
     ) { }
   }

   class AppService {
     @resolve('ServiceA') serviceA: ServiceA;
   }
   ```

## 🛠️ Advanced Features

### Container Cloning

Create multiple container instances for different scopes or testing:

```typescript
class ServiceA { }
const container = DependencyInjectionContainer.instance;
container.setup().bind(ServiceA);

// Clone with all bindings and options
const container2 = container.clone();
console.log(container === container2); // false

const service = container2.resolve(ServiceA); // Works with cloned container
```

`CloneMode` controls which instances the clone takes over:

- `CloneMode.ConfigurationOnly` keeps only the instances registered with `toInstance()`.
- `CloneMode.KeepInstances` (default) keeps the instances registered with `toInstance()` and additionally the instances created on resolve.

```typescript
import { CloneMode } from '@run-js/dependency-injection-core';

container.setup().bindSingleton(ServiceA);
const serviceA = container.resolve(ServiceA);

container.clone().resolve(ServiceA) === serviceA; // true
container.clone(CloneMode.ConfigurationOnly).resolve(ServiceA) === serviceA; // false - created again
```

Cloning is available without a license. A clone made without a license preserves `throwIfNotFound` and uses the free defaults for Premium options. With a valid Premium license, it also preserves the configured Premium option values.

Know these limits of a clone:
- Singletons created after `clone()` are separate. Which existing instances the clone keeps depends on `CloneMode`.
- Resolving `'DependencyInjectionContainer'` from a clone returns the original static instance.
- `@resolve` / `@resolveAll` properties always resolve from the static instance, also in objects the clone created. Constructor parameters resolve from the clone.

### DI Container Self Binding

The container automatically binds itself for circular references:

```typescript
const container = DependencyInjectionContainer.instance;

// Container is self-registered
const dic = container.resolve(DependencyInjectionContainer);
console.log(container === dic); // true

// Also works with property injection
class ServiceA {
  @resolve('DependencyInjectionContainer') container: IDependencyInjectionContainer;

  resolveSomething() {
    return this.container.resolve('SomeService');
  }
}
```

### 🧪 Testing

Reset the container between tests with `clearBindings()`, then bind fakes with `toInstance()`. Lazy properties resolve on first access, so the class under test needs no constructor wiring. `clearBindings()` also removes the container's [self binding](#di-container-self-binding), all `@bind` registrations, and the `@resolveParameter` / `@resolveAllParameter` settings; modules are not imported again, so re-bind what a test needs:

```typescript
class UserService {
  @resolve('IUserRepository') repository: IUserRepository;
  getName(id: number) { return this.repository.find(id).name; }
}

beforeEach(() => {
  DependencyInjectionContainer.instance.clearBindings();
});

it('returns the user name', () => {
  const fake: IUserRepository = { find: () => ({ id: 1, name: 'Alice' }) };
  DependencyInjectionContainer.instance.setup().bind('IUserRepository').toInstance(fake);

  expect(new UserService().getName(1)).toBe('Alice');
});
```

### Disposal & Cleanup 🔒 Premium

The container supports automatic disposal of services when the container is disposed. This is useful for cleaning up resources like database connections, file handles, or other external resources. Disposal and auto-dispose configuration require a Premium license.

> 💡 **Premium feature:** `dispose()` and all auto-dispose options require a valid Premium license. Auto-dispose is disabled by default. See [Auto-Dispose Options](#-auto-dispose-options--premium) for all settings.

#### IDisposable Interface

A convenience interface is provided for services that require cleanup:

```typescript
import { IDisposable } from '@run-js/dependency-injection-core';

class DatabasePool implements IDisposable {
  private pool: Pool;

  dispose(): void {
    this.pool.end();
  }
}
```

#### Explicit Disposer Callback 🔒 Premium

Register a custom cleanup function per binding using `.disposer()`:

```typescript
const container = DependencyInjectionContainer.instance;

// Explicit disposer for singletons
container.setup()
  .bind(DatabasePool).asSingleton()
  .disposer(pool => pool.end());

// Explicit disposer for transients (requires autoDisposeTrackTransients)
container.setOption('autoDisposeTrackTransients', true);
container.setup()
  .bind(TempFileService)
  .disposer(service => service.cleanup());

// Dispose all - calls every registered disposer
await container.dispose();
```

#### Auto-Dispose by Method Name 🔒 Premium

When `autoDisposeEnabled` is `true`, the container automatically calls a matching method on each service - no `.disposer()` needed:

```typescript
container.setOption('autoDisposeEnabled', true);
// Default methodNames: ['dispose']
// Customize: container.setOption('autoDisposeMethodNames', ['dispose', 'close', 'destroy']);

@bindSingleton()
class CacheService implements IDisposable {
  dispose(): void { /* cleanup */ }
}

await container.dispose(); // CacheService.dispose() called automatically
```

Methods are checked in order and **only the first match** is called. Services with an explicit `.disposer()` callback are **not** auto-disposed.

#### Tracking Transient Instances 🔒 Premium

By default, only singletons are disposed. Enable the Premium `autoDisposeTrackTransients` option to also dispose transient instances:

```typescript
container.setOption('autoDisposeEnabled', true);
container.setOption('autoDisposeTrackTransients', true);

@bind()
class RequestHandler implements IDisposable {
  dispose(): void { /* cleanup */ }
}

const handler = container.resolve(RequestHandler);
await container.dispose(); // handler.dispose() called
```

> ⚠️ **Warning:** Tracked transients are held via `WeakRef`, so garbage-collected instances are skipped. However, the tracking entries themselves consume a small amount of memory per resolved instance until the container is disposed.

For configuration details, see [Auto-Dispose Options](#-auto-dispose-options--premium).

## ⚡ Performance

The container uses an internal `Map`-based index for service lookups, ensuring **O(1) resolution time** regardless of how many bindings are registered. Automated performance tests run against **1,000,000 bindings** to verify this.

### Scaling Test (O(1) Verification)

| Operation | Bindings | Time | Notes |
|---|---|---|---|
| **Setup (bind)** | 1,000 | ~0.19 ms | Baseline |
| **Setup (bind)** | 1,000,000 | ~631.71 ms | Registering 1M services with instances |
| **resolve** (1k bindings) | 1,000 | ~0.30 ms / 5,000 calls | Baseline |
| **resolve** (1M bindings) | 1,000,000 | ~0.28 ms / 5,000 calls | Scaling factor ~0.95 - no meaningful degradation |

> The **scaling factor** (time at 1M bindings ÷ time at 1k bindings) remains close to 1.0 for `resolve`, empirically supporting O(1) lookup time. If resolution were O(n), this ratio would be ~1,000x.

### Competitor Benchmark

**Fastest in every scenario:** @run-js/di beats the runner-up tsyringe (14.6M+ weekly downloads) in combined bind + resolve time by **~66% on instance bindings**, **~35% on class bindings** and **~29% on singleton bindings**, and InversifyJS by **~85%**. All of this in a **35.3 kB uncompressed ESM production bundle**.

All libraries are benchmarked under identical conditions: each library and mode in its own standalone Node.js process, same V8 engine, same JIT warmup methodology - no test framework involved. Numbers below are **averaged across 25 independent runs**. **"all off"** disables all extra features (`interfaceMode`, `pluralMode`, case-insensitive matching) for a fair apples-to-apples comparison; **"all on"** enables every option except logging, showing real-world overhead.

**Instance Bindings** (10k services, 50k resolve calls):

| Library | Weekly Downloads | Bind | Resolve |
|---|---|---|---|
| **@run-js/di (all off)** | - | ~1.81 ms | ~5.22 ms |
| **@run-js/di (all on)** | - | ~1.97 ms | ~7.09 ms |
| tsyringe | 14,621,113 | ~4.20 ms | ~16.28 ms |
| InversifyJS | 2,514,825 | ~24.89 ms | ~20.82 ms |
| Awilix | 636,094 | ~13.04 ms | ~14.51 ms |
| TypeDI | 530,940 | ~271.80 ms | ~1,312.47 ms |

**Class/Transient Bindings** (5k services, 50k resolve calls):

| Library | Weekly Downloads | Bind | Resolve |
|---|---|---|---|
| **@run-js/di (all off)** | - | ~1.11 ms | ~11.00 ms |
| **@run-js/di (all on)** | - | ~1.14 ms | ~12.66 ms |
| tsyringe | 14,621,113 | ~1.30 ms | ~17.46 ms |
| InversifyJS | 2,514,825 | ~16.28 ms | ~23.61 ms |
| Awilix | 636,094 | ~20.97 ms | ~20.16 ms |
| TypeDI | 530,940 | ~76.62 ms | ~617.11 ms |

**Singleton Bindings** (5k services over 5 classes, 50k resolve calls including the first resolve of every binding):

| Library | Weekly Downloads | Bind | Resolve |
|---|---|---|---|
| **@run-js/di (all off)** | - | ~1.25 ms | ~10.26 ms |
| **@run-js/di (all on)** | - | ~1.34 ms | ~5.31 ms |
| tsyringe | 14,621,113 | ~1.49 ms | ~14.68 ms |
| InversifyJS | 2,514,825 | ~15.91 ms | ~22.45 ms |
| Awilix | 636,094 | ~21.14 ms | ~15.88 ms |
| TypeDI | 530,940 | ~74.76 ms | ~670.88 ms |

> "all on" includes `singletonsPerClass`, so all singleton bindings of one class share one instance (5 instances instead of 5,000).

**Memory** (one container, heap growth after forced GC, keys and registered values excluded):

| Library | 10k Instances Bound | Resolved | 5k Classes Bound | Resolved |
|---|---|---|---|---|
| **@run-js/di (all off)** | ~1.95 MB | ~4.30 MB | ~0.99 MB | ~2.72 MB |
| **@run-js/di (all on)** | ~2.22 MB | ~4.57 MB | ~1.13 MB | ~2.82 MB |
| tsyringe | ~3.38 MB | ~4.97 MB | ~1.68 MB | ~2.47 MB |
| InversifyJS | ~9.05 MB | ~16.33 MB | ~4.49 MB | ~15.75 MB |
| Awilix | ~1.78 MB | ~1.79 MB | ~6.30 MB | ~6.32 MB |
| TypeDI | ~1.06 MB | ~1.08 MB | ~0.54 MB | ~0.57 MB |

> Measured on a desktop machine, **averaged across 25 runs**. Every library and mode benchmarked in its own standalone Node.js process (no Jest or other test framework). Download counts from npm (12th Oct 2026). **"all off"** = `caseSensitive: true`, `interfaceMode: false`, `pluralMode: false`. **"all on"** = all options enabled except logging.

## ⚙️ Configuration Options

The container provides flexible configuration options to customize its behavior. Use `getOption()` to read an option and `setOption()` to change one:

```typescript
const container = DependencyInjectionContainer.instance;
const caseSensitive = container.getOption('caseSensitive');
container.setOption('caseSensitive', false);
```

Only `throwIfNotFound` can be changed without a license. Setting any other option without a license throws `Option '<key>' requires a premium license.`

Options belong to one container. `setLicense()` applies the Premium defaults only to the container it is called on, so call it on `DependencyInjectionContainer.instance` when you use decorators. Calling `setLicense()` again resets `caseSensitive`, `interfaceMode`, `pluralMode`, and `singletonsPerClass` to the Premium defaults.

### 🔤 Case Sensitivity 🔒 Premium

- **Without license (fixed):** `true` (case-sensitive)
- **Premium default (after `setLicense`):** `false` (case-insensitive)

```typescript
@bindSingleton()
class ServiceA { }

// This resolves to the registered service
const service1 = container.resolve(ServiceA);

// Enable case-insensitive matching
container.setOption('caseSensitive', false);
const service2 = container.resolve('servicea');
console.log(service1 === service2); // true
```

### 🚫 Throw If Not Found

**Default: `true`** - Container throws errors when services are not found.

```typescript
// Default behavior - throws error
try {
  container.resolve('NonExistentService');
} catch (error) {
  console.log('Service not found!');
}

// Return undefined instead of throwing
container.setOption('throwIfNotFound', false);
const service = container.resolve('NonExistentService'); // undefined

// resolveAll returns empty array instead of throwing
const services = container.resolveAll('NonExistentService'); // []

// Override per call with the third parameter; the fourth names the caller in the error message
const optional = container.resolve('NonExistentService', undefined, false); // undefined
const required = container.resolve('NonExistentService', undefined, true, 'CheckoutService'); // throws "No binding found for 'NonExistentService' while resolving for 'CheckoutService'."
```

`resolve(serviceTypeOrClass, specification?, throwIfNotFound?, callerName?)` and `resolveAll(...)` share this signature.

### 🔗 Interface Mode 🔒 Premium

- **Without license (fixed):** `false` (disabled)
- **Premium default (after `setLicense`):** `true` (enabled)

```typescript
// Premium default - only needed if it was switched off
container.setOption('interfaceMode', true);

// Service bound without 'I' prefix
@bind()
class UserService implements IUserService { }

// Can resolve with interface name
const service = container.resolve('IUserService');
console.log(service instanceof UserService); // true

// Service bound with 'I' prefix
@bind('IOtherService')
class OtherService implements IOtherService { }

// Can resolve without 'I' prefix
const other = container.resolve('OtherService');
console.log(other instanceof OtherService); // true

// Works in decorators too
class AppService {
  @resolve() userService: IUserService; // Matches 'UserService' (needs caseSensitive: false, the Premium default)
  @resolve() otherService: IOtherService; // Matches 'IOtherService'
}
```

> ⚠️ If both `UserService` and `IUserService` are bound, `resolve('IUserService')` finds both and throws `More than 1 binding found`.

### 📦 Plural Mode 🔒 Premium

- **Without license (fixed):** `false` (disabled)
- **Premium default (after `setLicense`):** `true` (enabled)

Plural mode applies to `resolveAll`, `@resolveAll`, and `@resolveAllParameter` only. A name ending in `s` also matches the name without the trailing `s`.

```typescript
// Premium default - only needed if it was switched off
container.setOption('pluralMode', true);

@bind()
class NotificationService implements INotificationService { }

class AppService {
  // 'notificationServices' matches 'INotificationService'
  @resolveAll() notificationServices: INotificationService[];

  // Also works in constructor parameters
  constructor(@resolveAll() notificationServices: INotificationService[]) { }
}

// Manual plural resolution
const services: IService[] = container.resolveAll('services'); // Matches 'service'
```

### 🏭 Singletons Per Class 🔒 Premium

- **Without license (fixed):** `false` (disabled)
- **Premium default (after `setLicense`):** `true` (enabled)

```typescript
// Premium default - only needed if it was switched off
container.setOption('singletonsPerClass', true);

class ConfigService { }

// Multiple bindings of same class share instance
container.setup()
  .bindSingleton(ConfigService, 'config')
  .bindSingleton(ConfigService, 'appConfig');

const config1 = container.resolve('config');
const config2 = container.resolve('appConfig');
console.log(config1 === config2); // true
```

### 🔌 Resolve All Interceptor 🔒 Premium

- **Without license (fixed):** `undefined` (no interceptor)
- **Premium default (after `setLicense`):** `undefined` (no interceptor; configure it with `setOption()`)

Custom processing of `resolveAll` results:

```typescript
interface IPlugin { priority: number; }
class PluginA implements IPlugin { priority = 1; }
class PluginB implements IPlugin { priority = 2; }

container.setup()
  .bind('IPlugin').toClass(PluginB) // bind B before A
  .bind('IPlugin').toClass(PluginA);

// Sort by priority
container.setOption('resolveAllInterceptor', (serviceType, spec, throwIfNotFound, instances) => {
  if (serviceType === 'IPlugin') {
    return instances.sort((a, b) => a.priority - b.priority);
  }
  return instances;
});

const plugins = container.resolveAll('IPlugin');
console.log(plugins[0].priority); // 1
console.log(plugins[1].priority); // 2
```

### 📝 Logging 🔒 Premium

- **Without license (fixed):** `loggingEnabled: false`, `loggingLogMethod: console.log`
- **Premium default (after `setLicense`):** `loggingEnabled: false`, `loggingLogMethod: console.log` (opt-in)

Enable detailed logging for debugging:

```typescript
// Enable logging
container.setOption('loggingEnabled', true);

// Custom log method
container.setOption('loggingLogMethod', (message) => {
  console.log(`[DI Container] ${message}`);
});

// Now all operations will be logged
const service = container.resolve(SomeService);
// Output: [DI Container] DIC: Resolving single bindings for serviceType SomeService.
```

### 🗑️ Auto-Dispose Options 🔒 Premium

- **Without license (fixed):** `autoDisposeEnabled: false`, `autoDisposeMethodNames: ['dispose']`, `autoDisposeTrackTransients: false`
- **Premium default (after `setLicense`):** `autoDisposeEnabled: false`, `autoDisposeMethodNames: ['dispose']`, `autoDisposeTrackTransients: false` (opt-in)

Configure automatic disposal of services when the container is disposed. See [Disposal & Cleanup](#disposal--cleanup--premium) for usage examples.

```typescript
// Enable auto-dispose
container.setOption('autoDisposeEnabled', true);

// Configure which method names to look for (checked in order, first match wins)
container.setOption('autoDisposeMethodNames', ['dispose', 'close', 'destroy']);

// Track and dispose transient instances (uses WeakRef)
container.setOption('autoDisposeTrackTransients', true);

// Dispose the container - calls all disposers
await container.dispose();
```

> 💡 Services with an explicit `.disposer()` callback always use that callback; auto-dispose only applies to services **without** one.

## 💎 Premium Features

Core binding, resolution, configuration of `throwIfNotFound`, and cloning are available without a license. Premium features are enabled by setting a valid license key on the container:

```typescript
const container = DependencyInjectionContainer.instance;
await container.setLicense('your-license-key');
```

Premium includes `dispose()` and these configuration options: `caseSensitive`, `interfaceMode`, `pluralMode`, `singletonsPerClass`, `resolveAllInterceptor`, `loggingEnabled`, `loggingLogMethod`, `autoDisposeEnabled`, `autoDisposeMethodNames`, and `autoDisposeTrackTransients`.

After a valid license is set, the convenience defaults are applied: `caseSensitive` becomes `false`, while `interfaceMode`, `pluralMode`, and `singletonsPerClass` become `true`. Other Premium options remain opt-in.

Buy a Premium or test license at [store.run-js.com/dependency-injection-core](https://store.run-js.com/dependency-injection-core).

## 🐛 Troubleshooting

### Decorators Not Working

**Issue**: `@bind`, `@resolve`, or other decorators aren't functioning.

**Solutions**:

1. **Enable TypeScript experimental decorators** in your `tsconfig.json`:
```json
{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}
```

2. **Target ES2022 with useDefineForClassFields disabled**:
```json
{
  "compilerOptions": {
    "target": "ES2022",
    "useDefineForClassFields": false
  }
}
```

### Services Not Found

**Issue**: Container throws `No binding found for '<serviceType>'`.

**Solutions**:

1. **Ensure services are imported/loaded when using decorators**:
```typescript
// Import the file containing @bind decorators
import './services/UserService';

// Or use barrel exports in index.ts
export * from './services/UserService';
```

2. **Verify service names and specifications**:
```typescript
// Registration
container.setup().bind(UserService, 'UserService', 'v2');

// Resolution - must match exactly
const service = container.resolve('UserService', 'v2');
```

### Circular Dependencies

**Issue**: Services have circular references.

**Solution**: The container automatically **detects circular dependencies** and throws a descriptive error:

```
Cyclic dependency detected for: serviceType: ServiceA (class: ServiceA) >>> serviceB >>> serviceA.
```

**Recommended approaches**:

1. **Use property injection instead of constructor injection** - see [Cyclic Dependencies](#cyclic-dependencies) for a three-file example:
```typescript
@bind()
class ServiceA {
  @resolve('ServiceB') serviceB: ServiceB; // Lazy property injection
}

@bind()
class ServiceB {
  @resolve('ServiceA') serviceA: ServiceA; // Lazy property injection
}
```

2. **Refactor to remove circular dependencies**:
```typescript
// Extract shared functionality to a third service
@bind()
class SharedService { }

@bind()
class ServiceA {
  constructor(@resolve('SharedService') private shared: SharedService) { }
}

@bind()
class ServiceB {
  constructor(@resolve('SharedService') private shared: SharedService) { }
}
```

## 🔧 Requirements

- TypeScript 4.4+ (from 2021 or newer)
- Node.js 18.4+, or a browser with WebCrypto Ed25519 support (Chrome/Edge 137+, Firefox 130+, Safari 17+) - required for license validation
- Decorator support enabled in TypeScript configuration

Make sure your `tsconfig.json` includes:

```json
{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}
```

## 📄 License Information

This project is licensed under the [End-User License Agreement](https://dependency-injection-core.run-js.com/#/license).

Personal, non-commercial use is free. Any use in the course of business or on behalf of a business requires a valid Business License, whether or not the business generates revenue. A valid Premium license is additionally required for the Premium features documented above. Purchase licenses at [store.run-js.com/dependency-injection-core](https://store.run-js.com/dependency-injection-core).

## 🌐 About Rudolf Run Ltd

> **We stand for uncompromising commitment to quality.**<br>
> Our philosophy is that software should meet the highest standards, without cutting corners or sacrificing functionality.<br>
> And because we believe in fairness, everyone should have access to the best software, regardless of budget.

- 📍 Larnaca, Cyprus
- 🌐 [http://rudolf.run](http://rudolf.run)
- 📧 [support@run-js.com](mailto:support@run-js.com)

---

## 🏷️ Keywords

<div align="center">

`dependency injection` • `dependency-injection` • `di` • `ioc` • `container` • `dependency inversion` • `inversion of control` • `inversion-of-control` • `inversion of control container` • `dependency-inversion` • `typescript` • `javascript` • `node` • `decorators` • `constructor-injection` • `property-injection` • `lazy-loading` • `lazy-properties` • `lazy-injection` • `circular-dependency` • `singleton` • `factory` • `resolve-all` • `named-bindings` • `service-container` • `lightweight` • `zero-dependencies`

---

**Made by [Rudolf Run Ltd](https://rudolf.run) with 🤯🤬😎 fighting JavaScript so you don't have to 😃.**
<br>
**Code and documentation copyright 2026 by [Rudolf Run Ltd](http://rudolf.run)**


</div>
