2025-11-17 19:02:15 +00:00
|
|
|
import { Exception } from "Helpers/Exception";
|
2025-11-27 12:39:08 +00:00
|
|
|
import type { Component } from "obsidian";
|
2025-11-17 19:02:15 +00:00
|
|
|
|
2025-11-10 21:47:18 +00:00
|
|
|
const services = new Map<symbol, unknown>();
|
2025-09-08 14:50:06 +00:00
|
|
|
|
2025-11-17 19:02:15 +00:00
|
|
|
export function RegisterSingleton<T>(type: symbol, instance: T) {
|
2025-09-08 14:50:06 +00:00
|
|
|
services.set(type, instance);
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-17 19:02:15 +00:00
|
|
|
export function RegisterTransient<T>(type: symbol, factory: () => T) {
|
2025-09-08 14:50:06 +00:00
|
|
|
services.set(type, factory);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function Resolve<T>(type: symbol): T {
|
|
|
|
|
const service = services.get(type);
|
2026-01-28 21:23:47 +00:00
|
|
|
|
2025-09-08 14:50:06 +00:00
|
|
|
if (!service) {
|
2025-11-17 19:02:15 +00:00
|
|
|
Exception.throw(`Service not found for type: ${type.description}`);
|
2025-09-08 14:50:06 +00:00
|
|
|
}
|
|
|
|
|
|
2025-11-27 12:39:08 +00:00
|
|
|
if (typeof service === "function") {
|
|
|
|
|
// It"s a transient factory, return a new instance
|
2025-11-10 20:37:13 +00:00
|
|
|
return (service as () => T)();
|
2025-09-08 14:50:06 +00:00
|
|
|
}
|
|
|
|
|
|
2025-11-27 12:39:08 +00:00
|
|
|
// It"s a singleton, return the existing instance
|
2025-09-08 14:50:06 +00:00
|
|
|
return service as T;
|
2025-10-30 12:15:35 +00:00
|
|
|
}
|
|
|
|
|
|
2026-01-28 21:23:47 +00:00
|
|
|
export function TryResolve<T>(type: symbol): T | undefined {
|
|
|
|
|
if (services.has(type)) {
|
|
|
|
|
return Resolve<T>(type);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-17 19:02:15 +00:00
|
|
|
export function DeregisterAllServices() {
|
2025-11-27 12:39:08 +00:00
|
|
|
services.forEach((service) => {
|
2026-05-25 17:22:07 +00:00
|
|
|
if (!service || typeof service !== "object") {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if ("dispose" in service && typeof service.dispose === "function") {
|
|
|
|
|
(service as { dispose: () => void }).dispose();
|
|
|
|
|
}
|
|
|
|
|
if ("unload" in service) {
|
2025-11-27 12:39:08 +00:00
|
|
|
(service as Component).unload();
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-10-30 12:15:35 +00:00
|
|
|
services.clear();
|
2025-09-08 14:50:06 +00:00
|
|
|
}
|