Skip to content
Buy me a coffee

Circular dependencies

A cycle is a chain of dependencies that leads back to where it started: OrderService needs PaymentService, which needs OrderService. Constructor injection can’t satisfy that directly, since each constructor needs the other’s finished instance first. The container resolves it anyway, for singleton, scoped and transient services alike.

class
class OrderService
OrderService
{
constructor(private readonly
OrderService.payments: PaymentService
payments
:
class PaymentService
PaymentService
) {}
OrderService.checkout(id: string): string
checkout
(
id: string
id
: string) {
return this.
OrderService.payments: PaymentService
payments
.
PaymentService.charge(id: string): string
charge
(
id: string
id
);
}
OrderService.label(id: string): string
label
(
id: string
id
: string) {
return `order ${
id: string
id
}`;
}
}
class
class PaymentService
PaymentService
{
constructor(private readonly
PaymentService.orders: OrderService
orders
:
class OrderService
OrderService
) {}
PaymentService.charge(id: string): string
charge
(
id: string
id
: string) {
return `charged ${this.
PaymentService.orders: OrderService
orders
.
OrderService.label(id: string): string
label
(
id: string
id
)}`; // uses the partner in a method: fine
}
}
const
const provider: ServiceProvider
provider
= new
new ServiceCollection(): ServiceCollection

Collects service registrations, then builds a

ServiceProvider

. Modeled on .NET's IServiceCollection.

@example

const services = new ServiceCollection();
services.addSingleton(Logger, ConsoleLogger);
services.addScoped(UserService, [Logger]);
const provider = services.buildServiceProvider({ validateScopes: true });

ServiceCollection
()
.
ServiceCollection.addSingleton<OrderService, [payments: PaymentService]>(token: Newable<OrderService, [payments: PaymentService]>, dependencies: readonly [payments: Token<PaymentService>]): ServiceCollection (+4 overloads)

Registers a singleton: one instance for the root provider and all its scopes.

  • addSingleton(Class) / addSingleton(Class, [deps]): the class is its own token.
  • addSingleton(token, Implementation, [deps]): deps are checked against the constructor's parameters.
  • addSingleton(token, (provider) => instance): a factory, may be async.

addSingleton
(
class OrderService
OrderService
, [
class PaymentService
PaymentService
])
.
ServiceCollection.addSingleton<PaymentService, [orders: OrderService]>(token: Newable<PaymentService, [orders: OrderService]>, dependencies: readonly [orders: Token<OrderService>]): ServiceCollection (+4 overloads)

Registers a singleton: one instance for the root provider and all its scopes.

  • addSingleton(Class) / addSingleton(Class, [deps]): the class is its own token.
  • addSingleton(token, Implementation, [deps]): deps are checked against the constructor's parameters.
  • addSingleton(token, (provider) => instance): a factory, may be async.

addSingleton
(
class PaymentService
PaymentService
, [
class OrderService
OrderService
])
.
ServiceCollection.buildServiceProvider(options?: BuildOptions): ServiceProvider

Builds the provider. Registrations are copied, so changing this collection afterwards does not affect providers already built.

buildServiceProvider
();
const
const orders: OrderService
orders
= await
const provider: ServiceProvider
provider
.
ServiceProvider.getRequiredService<OrderService>(token: Token<OrderService>): Promise<OrderService>

Resolves token, throwing ServiceNotFoundError if it is not registered.

getRequiredService
(
class OrderService
OrderService
);
const orders: OrderService
orders
.
OrderService.checkout(id: string): string
checkout
('42'); // 'charged order 42'

When resolving OrderService reaches OrderService again, the container hands PaymentService a proxy for the OrderService still being built, instead of failing. Once OrderService’s constructor returns, the proxy forwards every property access, method call and assignment to the real instance.

  • Identity holds. Everyone in the cycle ends up with the same object: orders.payments.orders === orders. That object is the proxy: for a service that took part in a cycle, the proxy is the canonical instance every caller gets. instanceof works, and orders.constructor is the real class.
  • Methods are bound to the real instance, so #private fields and this work as usual. Each method is bound once, so orders.checkout === orders.checkout holds (removing an event listener works).
  • Every lifetime. Singleton and scoped cycles share one instance per root or scope. Transient cycles work within one resolution: each getRequiredService builds a fresh cycle.
  • Factories are part of the chain. A factory receives a provider that carries the current resolution path, so a cycle that passes through provider.getRequiredService(...) inside a factory is detected and resolved the same way. Resolve through that provider, not one captured from outside the factory.
  • Concurrent resolutions. If two resolutions start from opposite ends of a cycle at the same time (Promise.all([get(A), get(B)])), each would wait for the other forever. The container detects that wait and hands out a proxy, so both finish and still share the same instances.

Don’t touch a partner in the constructor

Section titled “Don’t touch a partner in the constructor”

The proxy can only forward to an instance that exists. Using a cycle partner inside a constructor, before the partner’s own constructor has returned, throws a CircularDependencyError with the path:

class
class A
A
{
constructor(readonly
A.b: B
b
:
class B
B
) {}
A.name: string
name
= 'A';
}
class
class B
B
{
readonly
B.label: string
label
: string;
constructor(
a: A
a
:
class A
A
) {
this.
B.label: string
label
= `B of ${
a: A
a
.
A.name: string
name
}`; // A's constructor hasn't finished yet
}
}
const
const provider: ServiceProvider
provider
= new
new ServiceCollection(): ServiceCollection

Collects service registrations, then builds a

ServiceProvider

. Modeled on .NET's IServiceCollection.

@example

const services = new ServiceCollection();
services.addSingleton(Logger, ConsoleLogger);
services.addScoped(UserService, [Logger]);
const provider = services.buildServiceProvider({ validateScopes: true });

ServiceCollection
().
ServiceCollection.addSingleton<A, [b: B]>(token: Newable<A, [b: B]>, dependencies: readonly [b: Token<B>]): ServiceCollection (+4 overloads)

Registers a singleton: one instance for the root provider and all its scopes.

  • addSingleton(Class) / addSingleton(Class, [deps]): the class is its own token.
  • addSingleton(token, Implementation, [deps]): deps are checked against the constructor's parameters.
  • addSingleton(token, (provider) => instance): a factory, may be async.

addSingleton
(
class A
A
, [
class B
B
]).
ServiceCollection.addSingleton<B, [a: A]>(token: Newable<B, [a: A]>, dependencies: readonly [a: Token<A>]): ServiceCollection (+4 overloads)

Registers a singleton: one instance for the root provider and all its scopes.

  • addSingleton(Class) / addSingleton(Class, [deps]): the class is its own token.
  • addSingleton(token, Implementation, [deps]): deps are checked against the constructor's parameters.
  • addSingleton(token, (provider) => instance): a factory, may be async.

addSingleton
(
class B
B
, [
class A
A
]).
ServiceCollection.buildServiceProvider(options?: BuildOptions): ServiceProvider

Builds the provider. Registrations are copied, so changing this collection afterwards does not affect providers already built.

buildServiceProvider
();
try {
await
const provider: ServiceProvider
provider
.
ServiceProvider.getRequiredService<A>(token: Token<A>): Promise<A>

Resolves token, throwing ServiceNotFoundError if it is not registered.

getRequiredService
(
class A
A
);
} catch (
var error: unknown
error
) {
if (
var error: unknown
error
instanceof
class CircularDependencyError

A service in a dependency cycle was used before its constructor finished.

CircularDependencyError
) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@see ― source

console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@since ― v0.1.100

log
(
var error: CircularDependencyError
error
.
CircularDependencyError.path: readonly Token[]
path
.
ReadonlyArray<Token>.map<string>(callbackfn: (value: Token, index: number, array: readonly Token[]) => string, thisArg?: any): string[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
t: Token
t
) => (
t: Token
t
as
interface Function

Creates a new function.

Function
).
Function.name: string

Returns the name of the function. Function names are read-only and can not be changed.

name
)); // ['A', 'B', 'A']
// Circular dependency A → B → A: 'A' was used before its constructor finished. …
}
}

Store the reference in the constructor and use it later, in a method. Storing it is always safe; reading from it, calling it or spreading it is not, until the constructor chain completes.

If a constructor in a cycle throws (this error or any other), the services that already captured its proxy are evicted along with it. The next resolution rebuilds the whole cycle from scratch instead of handing out objects that point at an instance that never finished.

The proxy forwards everything except one thing: it can’t be frozen or sealed. Object.freeze(orders), Object.seal and Object.preventExtensions throw a TypeError for a service that took part in a cycle. Freeze inner data objects instead, or break the cycle.

getCircularDependencies() lists every cycle among plain registrations, and visualizeCircularDependencies() prints them. The graph below is built from a real ServiceCollection and colours each cycle it reports. Edit the registrations to break or create cycles.

5registrations
2cycles
0captive
0missing
LoggerSIInvoiceServiceTRAuditLogSIPaymentServiceSCOrderServiceSC
SI singletonSC scopedTR transient cycle captive dependencyClick a service to resolve it for real.
cycle: OrderService → PaymentService → InvoiceService → OrderService
cycle: AuditLog → AuditLog
const
const services: ServiceCollection
services
= new
new ServiceCollection(): ServiceCollection

Collects service registrations, then builds a

ServiceProvider

. Modeled on .NET's IServiceCollection.

@example

const services = new ServiceCollection();
services.addSingleton(Logger, ConsoleLogger);
services.addScoped(UserService, [Logger]);
const provider = services.buildServiceProvider({ validateScopes: true });

ServiceCollection
().
ServiceCollection.addSingleton<A, [b: B]>(token: Newable<A, [b: B]>, dependencies: readonly [b: Token<B>]): ServiceCollection (+4 overloads)

Registers a singleton: one instance for the root provider and all its scopes.

  • addSingleton(Class) / addSingleton(Class, [deps]): the class is its own token.
  • addSingleton(token, Implementation, [deps]): deps are checked against the constructor's parameters.
  • addSingleton(token, (provider) => instance): a factory, may be async.

addSingleton
(
class A
A
, [
class B
B
]).
ServiceCollection.addSingleton<B, [a: A]>(token: Newable<B, [a: A]>, dependencies: readonly [a: Token<A>]): ServiceCollection (+4 overloads)

Registers a singleton: one instance for the root provider and all its scopes.

  • addSingleton(Class) / addSingleton(Class, [deps]): the class is its own token.
  • addSingleton(token, Implementation, [deps]): deps are checked against the constructor's parameters.
  • addSingleton(token, (provider) => instance): a factory, may be async.

addSingleton
(
class B
B
, [
class A
A
]);
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@see ― source

console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@since ― v0.1.100

log
(
const services: ServiceCollection
services
.
ServiceCollection.visualizeCircularDependencies(): string

Every dependency cycle as text.

visualizeCircularDependencies
());
// Found 1 circular dependency:
//
// Circular Dependency 1:
// A → B → A

These diagnostics read the dependency arrays, so they can’t see dependencies resolved inside factories. More in Diagnostics.