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.
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.
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:
Resolves token, throwing ServiceNotFoundError if it is not registered.
getRequiredService(
classA
A);
} catch (
var error:unknown
error) {
if (
var error:unknown
errorinstanceof
classCircularDependencyError
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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
tas
interfaceFunction
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
SI singletonSC scopedTR transient cycle captive dependencyClick a service to resolve it for real.
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(
classB
B, [
classA
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).