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.
This commit is contained in:
2024-08-16 17:27:04 +02:00
committed by Max P.
parent 92a3482537
commit 64bd0883c8

View File

@@ -31,18 +31,19 @@ export function RegisterInstance<
return function (constructor: TargetType, ...args: unknown[]): void { return function (constructor: TargetType, ...args: unknown[]): void {
// Get the instance of the DI container // Get the instance of the DI container
const diContainer = TSinjex.getInstance(); const diContainer = TSinjex.getInstance();
let instance: InstanceType<TargetType>;
// Create a proxy to instantiate the class when needed (Lazy Initialization) // Create a proxy to instantiate the class when needed (Lazy Initialization)
let lazyProxy: unknown = new Proxy( let lazyProxy: unknown = new Proxy(
{}, {},
{ {
get(target, prop, receiver) { get(target, prop, receiver) {
let instance: InstanceType<TargetType>; if (instance == null) {
if (init) {
if (init) { instance = init(constructor);
instance = init(constructor); } else {
} else { instance = new constructor(...args);
instance = new constructor(...args); }
} }
lazyProxy = instance; lazyProxy = instance;
@@ -50,12 +51,12 @@ export function RegisterInstance<
return instance[prop as keyof InstanceType<TargetType>]; return instance[prop as keyof InstanceType<TargetType>];
}, },
set(target, prop, value, receiver) { set(target, prop, value, receiver) {
let instance: InstanceType<TargetType>; if (instance == null) {
if (init) {
if (init) { instance = init(constructor);
instance = init(constructor); } else {
} else { instance = new constructor(...args);
instance = new constructor(...args); }
} }
lazyProxy = instance; lazyProxy = instance;