Skip to Content
Guides@WithNew

@WithNew

By default, dependencies are singletons — the same instance is returned each time. Use @WithNew() to create a new instance on every injection.

Basic Usage

class A { id = Math.random(); } class B { constructor(@WithNew() @Inject(A) private a: A) {} getAId() { return this.a.id; } } const injector = new Injector([[A], [B]]); const b1 = injector.createInstance(B); const b2 = injector.createInstance(B); b1.getAId() !== b2.getAId(); // true - different instances

With Factory Items

let counter = 0; const ICounter = createIdentifier<number>("counter"); class MyService { constructor(@WithNew() @Inject(ICounter) public count: number) {} } const injector = new Injector([ [MyService], [ICounter, { useFactory: () => counter++ }], ]); injector.createInstance(MyService).count; // 0 injector.createInstance(MyService).count; // 1

Instances created with @WithNew() are not cached by the injector. You are responsible for disposing them when no longer needed.

Last updated on