Skip to content

Instantly share code, notes, and snippets.

@im4aLL
Created May 17, 2024 02:38
Show Gist options
  • Save im4aLL/ff228ed643bb34d6c5490b80ffea4409 to your computer and use it in GitHub Desktop.
Save im4aLL/ff228ed643bb34d6c5490b80ffea4409 to your computer and use it in GitHub Desktop.
Make any class singletone
interface InjectionInstanceInterface {
[key: string]: any;
}
interface ClassRef<T> extends Function {
new (...args: any[]): T;
}
class InjectService {
private instances: InjectionInstanceInterface = {};
instance<T>(classFn: ClassRef<T>): T {
const name = classFn.name;
if (!this.instances[name]) {
this.instances[name] = new classFn();
}
return this.instances[name];
}
}
export const Inject = new InjectService();
/*
Usage:
=======================================================
class ExampleClass {
example() {
console.log(`example class and example method`);
}
}
const instance1 = Inject.instance(ExampleClass);
const instance2 = Inject.instance(ExampleClass);
console.log(instance1 === instance2); // true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment