Files
vue-desktop/src/services/di/ServiceProvider.ts
2025-10-11 12:05:57 +08:00

146 lines
3.3 KiB
TypeScript

import { ServiceRegistry, ServiceIds } from './ServiceRegistry'
import type { IServiceContainer } from './IServiceContainer'
import { initializePendingServices } from './decorators'
/**
* 服务提供者
* 提供静态方法访问所有系统服务
*/
export class ServiceProvider {
private static container: IServiceContainer | null = null
private static initialized = false
/**
* 初始化服务提供者
* 注册并初始化所有服务
*/
public static initialize(): void {
if (this.initialized) {
return
}
const registry = ServiceRegistry.getInstance()
registry.registerAllServices()
this.container = registry.getContainer()
this.container.initialize()
// 初始化所有使用@Service装饰器的服务
initializePendingServices()
this.initialized = true
}
/**
* 获取服务实例
* @param id 服务ID
* @returns 服务实例
*/
public static getService<T>(id: string): T {
if (!this.container) {
throw new Error('服务提供者尚未初始化')
}
return this.container.getService<T>(id)
}
/**
* 获取资源服务
*/
public static getResourceService(): any {
return this.getService(ServiceIds.RESOURCE_SERVICE)
}
/**
* 获取窗口表单服务
*/
public static getWindowFormService(): any {
return this.getService(ServiceIds.WINDOW_FORM_SERVICE)
}
/**
* 获取沙箱引擎
*/
public static getSandboxEngine(): any {
return this.getService(ServiceIds.SANDBOX_ENGINE)
}
/**
* 获取生命周期管理器
*/
public static getLifecycleManager(): any {
return this.getService(ServiceIds.LIFECYCLE_MANAGER)
}
/**
* 获取系统服务
*/
public static getSystemService(): any {
return this.getService(ServiceIds.SYSTEM_SERVICE)
}
/**
* 获取事件构建器
*/
public static getEventBuilder(): any {
return this.getService(ServiceIds.EVENT_BUILDER)
}
/**
* 获取外部应用发现服务
*/
public static getExternalAppDiscovery(): any {
return this.getService(ServiceIds.EXTERNAL_APP_DISCOVERY)
}
/**
* 获取错误处理服务
*/
public static getErrorHandler(): any {
return this.getService(ServiceIds.ERROR_HANDLER)
}
/**
* 检查是否已初始化
*/
public static isInitialized(): boolean {
return this.initialized
}
/**
* 获取服务容器(仅用于高级场景)
*/
public static getContainer(): IServiceContainer | null {
return this.container
}
}
/**
* 创建服务工厂函数
* @param constructor 服务构造函数
* @param dependencyIds 依赖的服务ID数组
* @returns 服务工厂函数
*/
export function createServiceFactory<T>(
constructor: new (...args: any[]) => T,
dependencyIds: string[] = []
): (container: IServiceContainer) => T {
return (container: IServiceContainer) => {
const dependencies = dependencyIds.map((id) => container.getService(id))
return new constructor(...dependencies)
}
}
/**
* 服务装饰器,用于标记需要注入的服务
*/
export function Inject(serviceId: string): PropertyDecorator {
return (target: Object, propertyKey: string | symbol) => {
const descriptor = {
get: () => {
return ServiceProvider.getService(serviceId)
}
}
Object.defineProperty(target, propertyKey, descriptor)
}
}