From 64bd0883c8144eb1a56f47316aebeb56996f0fd6 Mon Sep 17 00:00:00 2001 From: Max P Date: Fri, 16 Aug 2024 17:27:04 +0200 Subject: [PATCH] Fix lazy initialization of instances in RegisterInstance Updated the lazy initialization logic to ensure the instance is created only once by moving the instance variable outside of the proxy handlers. This addresses potential redundant instance creation and improves efficiency and consistency in DI container operations. --- src/decorators/RegisterInstance.ts | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/decorators/RegisterInstance.ts b/src/decorators/RegisterInstance.ts index 5e34629..b04cb56 100644 --- a/src/decorators/RegisterInstance.ts +++ b/src/decorators/RegisterInstance.ts @@ -31,18 +31,19 @@ export function RegisterInstance< return function (constructor: TargetType, ...args: unknown[]): void { // Get the instance of the DI container const diContainer = TSinjex.getInstance(); + let instance: InstanceType; // Create a proxy to instantiate the class when needed (Lazy Initialization) let lazyProxy: unknown = new Proxy( {}, { get(target, prop, receiver) { - let instance: InstanceType; - - if (init) { - instance = init(constructor); - } else { - instance = new constructor(...args); + if (instance == null) { + if (init) { + instance = init(constructor); + } else { + instance = new constructor(...args); + } } lazyProxy = instance; @@ -50,12 +51,12 @@ export function RegisterInstance< return instance[prop as keyof InstanceType]; }, set(target, prop, value, receiver) { - let instance: InstanceType; - - if (init) { - instance = init(constructor); - } else { - instance = new constructor(...args); + if (instance == null) { + if (init) { + instance = init(constructor); + } else { + instance = new constructor(...args); + } } lazyProxy = instance;