From 49d7f2c37ee3221bd6f53f30503c47cdca7ae9ac Mon Sep 17 00:00:00 2001 From: Azure <983547216@qq.com> Date: Sat, 11 Oct 2025 11:30:44 +0800 Subject: [PATCH] di --- src/services/di/IServiceContainer.ts | 41 ++++++ src/services/di/ServiceContainerImpl.ts | 138 ++++++++++++++++++ src/services/di/ServiceProvider.ts | 141 +++++++++++++++++++ src/services/di/ServiceRegistry.ts | 177 +++++++++++++++++++++++ src/services/di/SystemBootstrapper.ts | 179 ++++++++++++++++++++++++ src/services/di/example.ts | 94 +++++++++++++ src/services/di/types.d.ts | 91 ++++++++++++ 7 files changed, 861 insertions(+) create mode 100644 src/services/di/IServiceContainer.ts create mode 100644 src/services/di/ServiceContainerImpl.ts create mode 100644 src/services/di/ServiceProvider.ts create mode 100644 src/services/di/ServiceRegistry.ts create mode 100644 src/services/di/SystemBootstrapper.ts create mode 100644 src/services/di/example.ts create mode 100644 src/services/di/types.d.ts diff --git a/src/services/di/IServiceContainer.ts b/src/services/di/IServiceContainer.ts new file mode 100644 index 0000000..e6a9192 --- /dev/null +++ b/src/services/di/IServiceContainer.ts @@ -0,0 +1,41 @@ +/** + * 服务容器接口 + * 负责管理和提供所有系统服务的实例 + */ +export interface IServiceContainer { + /** + * 注册服务 + * @param id 服务唯一标识符 + * @param factory 服务工厂函数 + * @param dependencies 依赖的服务ID数组 + */ + register(id: string, factory: ServiceFactory, dependencies?: string[]): void + + /** + * 获取服务实例 + * @param id 服务唯一标识符 + * @returns 服务实例 + * @throws 当服务未注册时抛出错误 + */ + getService(id: string): T + + /** + * 检查服务是否已注册 + * @param id 服务唯一标识符 + * @returns 是否已注册 + */ + has(id: string): boolean + + /** + * 初始化所有服务 + * 按照依赖关系顺序初始化服务 + */ + initialize(): void +} + +/** + * 服务工厂函数类型 + * @param container 服务容器实例 + * @returns 服务实例 + */ +export type ServiceFactory = (container: IServiceContainer) => T diff --git a/src/services/di/ServiceContainerImpl.ts b/src/services/di/ServiceContainerImpl.ts new file mode 100644 index 0000000..6087d65 --- /dev/null +++ b/src/services/di/ServiceContainerImpl.ts @@ -0,0 +1,138 @@ +import type { IServiceContainer, ServiceFactory } from './IServiceContainer' + +/** + * 服务注册信息接口 + */ +interface ServiceRegistration { + factory: ServiceFactory + dependencies: string[] + instance: T | null + initialized: boolean +} + +/** + * 服务容器实现 + * 使用工厂模式和依赖注入模式管理服务实例 + */ +export class ServiceContainerImpl implements IServiceContainer { + private services = new Map>() + private initializationStack: string[] = [] + private initialized = false + + /** + * 注册服务 + * @param id 服务唯一标识符 + * @param factory 服务工厂函数 + * @param dependencies 依赖的服务ID数组 + */ + public register(id: string, factory: ServiceFactory, dependencies: string[] = []): void { + if (this.initialized) { + throw new Error(`无法在容器初始化后注册服务: ${id}`) + } + + this.services.set(id, { + factory, + dependencies, + instance: null, + initialized: false + }) + } + + /** + * 获取服务实例 + * @param id 服务唯一标识符 + * @returns 服务实例 + * @throws 当服务未注册或发生循环依赖时抛出错误 + */ + public getService(id: string): T { + const registration = this.services.get(id) + + if (!registration) { + throw new Error(`未注册的服务: ${id}`) + } + + // 检测循环依赖 + if (this.initializationStack.includes(id)) { + throw new Error(`检测到循环依赖: ${this.initializationStack.join(' -> ')} -> ${id}`) + } + + // 如果服务实例尚未创建,则创建它 + if (!registration.instance) { + this.initializationStack.push(id) + + try { + // 首先确保所有依赖都已初始化 + for (const dependencyId of registration.dependencies) { + this.getService(dependencyId) + } + + // 创建服务实例 + registration.instance = registration.factory(this) + registration.initialized = true + } finally { + this.initializationStack.pop() + } + } + + return registration.instance + } + + /** + * 检查服务是否已注册 + * @param id 服务唯一标识符 + * @returns 是否已注册 + */ + public has(id: string): boolean { + return this.services.has(id) + } + + /** + * 初始化所有服务 + * 按照依赖关系顺序初始化服务 + */ + public initialize(): void { + if (this.initialized) { + return + } + + try { + // 初始化所有服务(按依赖顺序) + this.services.forEach((_, id) => { + this.getService(id) + }) + + this.initialized = true + } catch (error) { + console.error('服务容器初始化失败:', error) + throw error + } + } + + /** + * 获取所有已注册服务的ID列表 + * @returns 服务ID列表 + */ + public getRegisteredServices(): string[] { + return Array.from(this.services.keys()) + } + + /** + * 清除服务实例(用于测试) + * @param id 服务ID,如果不提供则清除所有服务 + */ + public clear(id?: string): void { + if (id) { + const registration = this.services.get(id) + if (registration) { + registration.instance = null + registration.initialized = false + } + } else { + this.services.forEach((registration) => { + registration.instance = null + registration.initialized = false + }) + this.initialized = false + } + } +} diff --git a/src/services/di/ServiceProvider.ts b/src/services/di/ServiceProvider.ts new file mode 100644 index 0000000..22d4193 --- /dev/null +++ b/src/services/di/ServiceProvider.ts @@ -0,0 +1,141 @@ +import { ServiceRegistry, ServiceIds } from './ServiceRegistry' +import type { IServiceContainer } from './IServiceContainer' + +/** + * 服务提供者 + * 提供静态方法访问所有系统服务 + */ +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() + + this.initialized = true + } + + /** + * 获取服务实例 + * @param id 服务ID + * @returns 服务实例 + */ + public static getService(id: string): T { + if (!this.container) { + throw new Error('服务提供者尚未初始化') + } + return this.container.getService(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( + 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) + } +} diff --git a/src/services/di/ServiceRegistry.ts b/src/services/di/ServiceRegistry.ts new file mode 100644 index 0000000..4bd6000 --- /dev/null +++ b/src/services/di/ServiceRegistry.ts @@ -0,0 +1,177 @@ +import type { IServiceContainer, ServiceFactory } from './IServiceContainer' +import { ServiceContainerImpl } from './ServiceContainerImpl' + +/** + * 服务ID常量 + */ +export enum ServiceIds { + RESOURCE_SERVICE = 'resourceService', + WINDOW_FORM_SERVICE = 'windowFormService', + SANDBOX_ENGINE = 'sandboxEngine', + LIFECYCLE_MANAGER = 'lifecycleManager', + SYSTEM_SERVICE = 'systemService', + EVENT_BUILDER = 'eventBuilder', + EXTERNAL_APP_DISCOVERY = 'externalAppDiscovery', + ERROR_HANDLER = 'errorHandler' +} + +/** + * 服务注册表 + * 负责注册所有系统服务 + */ +export class ServiceRegistry { + private static instance: ServiceRegistry + private container: IServiceContainer + + private constructor() { + this.container = new ServiceContainerImpl() + } + + /** + * 获取服务注册表单例 + */ + public static getInstance(): ServiceRegistry { + if (!ServiceRegistry.instance) { + ServiceRegistry.instance = new ServiceRegistry() + } + return ServiceRegistry.instance + } + + /** + * 获取服务容器实例 + */ + public getContainer(): IServiceContainer { + return this.container + } + + /** + * 注册所有服务 + * 注意:服务注册顺序应按照依赖关系排列 + */ + public registerAllServices(): void { + // 注册基本服务 - 这些服务没有其他依赖 + this.registerEventBuilder() + this.registerExternalAppDiscovery() + + // 注册核心服务 - 按照依赖关系顺序注册 + this.registerResourceService() + this.registerWindowFormService() + this.registerSandboxEngine() + this.registerLifecycleManager() + this.registerSystemService() + } + + /** + * 注册事件构建器服务 + */ + private registerEventBuilder(): void { + this.container.register(ServiceIds.EVENT_BUILDER, async () => { + const { EventBuilderImpl } = await import('@/events/impl/EventBuilderImpl') + return new EventBuilderImpl() + }) + } + + /** + * 注册外部应用发现服务 + */ + private registerExternalAppDiscovery(): void { + this.container.register(ServiceIds.EXTERNAL_APP_DISCOVERY, async () => { + // 延迟导入避免循环依赖 + const { externalAppDiscovery } = await import('../ExternalAppDiscovery') + return externalAppDiscovery + }) + } + + /** + * 注册资源服务 + */ + private registerResourceService(): void { + this.container.register( + ServiceIds.RESOURCE_SERVICE, + async (container) => { + // 延迟导入避免循环依赖 + const { ResourceService } = await import('../ResourceService') + return new ResourceService(container.getService(ServiceIds.EVENT_BUILDER)) + }, + [ServiceIds.EVENT_BUILDER] + ) + } + + /** + * 注册窗口表单服务 + */ + private registerWindowFormService(): void { + this.container.register( + ServiceIds.WINDOW_FORM_SERVICE, + async (container) => { + // 延迟导入避免循环依赖 + const { WindowFormService } = await import('../WindowFormService') + return new WindowFormService(container.getService(ServiceIds.EVENT_BUILDER)) + }, + [ServiceIds.EVENT_BUILDER] + ) + } + + /** + * 注册沙箱引擎服务 + */ + private registerSandboxEngine(): void { + this.container.register( + ServiceIds.SANDBOX_ENGINE, + async (container) => { + // 延迟导入避免循环依赖 + const { ApplicationSandboxEngine } = await import('../ApplicationSandboxEngine') + return new ApplicationSandboxEngine( + container.getService(ServiceIds.RESOURCE_SERVICE), + container + ) + }, + [ServiceIds.RESOURCE_SERVICE] + ) + } + + /** + * 注册生命周期管理器服务 + */ + private registerLifecycleManager(): void { + this.container.register( + ServiceIds.LIFECYCLE_MANAGER, + async (container) => { + // 延迟导入避免循环依赖 + const { ApplicationLifecycleManager } = await import('../ApplicationLifecycleManager') + return new ApplicationLifecycleManager( + container.getService(ServiceIds.RESOURCE_SERVICE), + container.getService(ServiceIds.SANDBOX_ENGINE), + container.getService(ServiceIds.WINDOW_FORM_SERVICE) + ) + }, + [ + ServiceIds.RESOURCE_SERVICE, + ServiceIds.SANDBOX_ENGINE, + ServiceIds.WINDOW_FORM_SERVICE, + ServiceIds.EXTERNAL_APP_DISCOVERY + ] + ) + } + + /** + * 注册系统服务集成服务 + */ + private registerSystemService(): void { + this.container.register( + ServiceIds.SYSTEM_SERVICE, + async (container) => { + // 延迟导入避免循环依赖 + const { SystemServiceIntegration } = await import('../SystemServiceIntegration') + return new SystemServiceIntegration(container) + }, + [ + ServiceIds.RESOURCE_SERVICE, + ServiceIds.WINDOW_FORM_SERVICE, + ServiceIds.SANDBOX_ENGINE, + ServiceIds.LIFECYCLE_MANAGER, + ServiceIds.EVENT_BUILDER + ] + ) + } +} diff --git a/src/services/di/SystemBootstrapper.ts b/src/services/di/SystemBootstrapper.ts new file mode 100644 index 0000000..8f51db9 --- /dev/null +++ b/src/services/di/SystemBootstrapper.ts @@ -0,0 +1,179 @@ +import { ServiceRegistry } from './ServiceRegistry' +import { ServiceProvider } from './ServiceProvider' +import { SystemServiceIntegration } from '../SystemServiceIntegration' +import { ServiceContainerImpl } from './ServiceContainerImpl' + +/** + * 系统启动器 + * 负责初始化整个系统,包括服务容器、服务注册和启动核心服务 + */ +export class SystemBootstrapper { + private static instance: SystemBootstrapper + private serviceContainer: ServiceContainerImpl + private systemService: SystemServiceIntegration | null = null + private initialized = false + + private constructor() { + this.serviceContainer = new ServiceContainerImpl() + } + + /** + * 获取系统启动器实例 + */ + public static getInstance(): SystemBootstrapper { + if (!SystemBootstrapper.instance) { + SystemBootstrapper.instance = new SystemBootstrapper() + } + return SystemBootstrapper.instance + } + + /** + * 启动整个系统 + * @param config 系统配置参数 + * @returns 启动成功返回true,失败返回false + */ + public async bootstrap(config?: { + debug?: boolean + autoCleanup?: boolean + cleanupInterval?: number + }): Promise { + if (this.initialized) { + console.warn('系统已经启动') + return true + } + + try { + console.log('开始启动系统...', config) + + // 1. 初始化服务提供者 + this.initializeServiceProvider() + + // 2. 初始化系统服务集成层 + this.initializeSystemService(config || {}) + + // 3. 启动所有服务 + await this.startAllServices() + + this.initialized = true + console.log('系统启动成功') + return true + } catch (error) { + console.error('系统启动失败:', error) + return false + } + } + + /** + * 初始化服务提供者 + * 注册并初始化所有服务 + */ + private initializeServiceProvider(): void { + console.log('初始化服务提供者...') + + // 初始化服务提供者,这会注册并初始化所有服务 + ServiceProvider.initialize() + console.log('服务提供者初始化完成') + } + + /** + * 初始化系统服务集成层 + * 创建并配置SystemServiceIntegration实例 + */ + private initializeSystemService(config: { + debug?: boolean + autoCleanup?: boolean + cleanupInterval?: number + }): void { + console.log('初始化系统服务集成层...') + + // 获取服务容器 + const container = ServiceRegistry.getInstance().getContainer() + + // 创建系统服务集成实例,使用传入的配置 + this.systemService = new SystemServiceIntegration(container, { + debug: config.debug ?? true, + autoCleanup: config.autoCleanup ?? true, + cleanupInterval: config.cleanupInterval ?? 5 * 60 * 1000 // 默认5分钟 + }) + + console.log('系统服务集成层初始化完成') + } + + /** + * 启动所有服务 + */ + private async startAllServices(): Promise { + console.log('启动所有服务...') + + if (!this.systemService) { + throw new Error('系统服务集成层未初始化') + } + + // 初始化系统服务 + await this.systemService.initialize() + + console.log('所有服务启动完成') + } + + /** + * 获取系统服务实例 + */ + public getSystemService(): SystemServiceIntegration | null { + return this.systemService + } + + /** + * 检查系统是否已初始化 + */ + public isInitialized(): boolean { + return this.initialized + } + + /** + * 关闭系统 + */ + public async shutdown(): Promise { + if (!this.initialized) { + console.warn('系统未启动') + return + } + + console.log('开始关闭系统...') + + try { + // 关闭系统服务 + if (this.systemService) { + await this.systemService.shutdown() + } + + // 重置状态 + this.systemService = null + this.initialized = false + + console.log('系统已关闭') + } catch (error) { + console.error('关闭系统时发生错误:', error) + } + } + + /** + * 重启系统 + */ + public async restart(): Promise { + console.log('重启系统...') + + try { + await this.shutdown() + await new Promise((resolve) => setTimeout(resolve, 1000)) + return await this.bootstrap() + } catch (error) { + console.error('重启系统失败:', error) + return false + } + } +} + +/** + * 导出系统启动器单例实例 + */ +export const systemBootstrapper = SystemBootstrapper.getInstance() diff --git a/src/services/di/example.ts b/src/services/di/example.ts new file mode 100644 index 0000000..c02b2e8 --- /dev/null +++ b/src/services/di/example.ts @@ -0,0 +1,94 @@ +/** + * 依赖注入系统使用示例 + */ + +// 1. 系统启动示例 - 通常在应用入口文件中使用 +import { systemBootstrapper } from './SystemBootstrapper' +import { ServiceProvider, Inject } from './ServiceProvider' +import { ServiceIds } from './ServiceRegistry' + +// 启动系统(通常在应用入口点调用一次) +async function startApplication() { + try { + console.log('正在启动应用...') + + // 启动整个系统,包括初始化服务容器和所有服务 + const success = await systemBootstrapper.bootstrap() + + if (!success) { + throw new Error('系统启动失败') + } + + console.log('应用启动成功!') + + // 应用初始化完成后,可以开始使用各种服务 + initializeApplication() + } catch (error) { + console.error('应用启动失败:', error) + } +} + +// 应用初始化 +function initializeApplication() { + // 2. 使用静态服务提供者访问服务 + const windowService = ServiceProvider.getWindowFormService() + const resourceService = ServiceProvider.getResourceService() + + console.log('访问服务示例:', { + windowServiceAvailable: !!windowService, + resourceServiceAvailable: !!resourceService + }) + + // 3. 创建并初始化一个使用依赖注入的组件 + const appComponent = new ApplicationComponent() + appComponent.initialize() +} + +// 4. 在组件中使用依赖注入 +class ApplicationComponent { + // 使用装饰器自动注入服务 + @Inject(ServiceIds.WINDOW_FORM_SERVICE) + private windowFormService: any + + @Inject(ServiceIds.RESOURCE_SERVICE) + private resourceService: any + + @Inject(ServiceIds.LIFECYCLE_MANAGER) + private lifecycleManager: any + + initialize() { + console.log('组件初始化,服务已注入:', { + windowFormService: !!this.windowFormService, + resourceService: !!this.resourceService, + lifecycleManager: !!this.lifecycleManager + }) + + // 使用注入的服务 + this.setupComponent() + } + + private setupComponent() { + // 示例:使用窗口服务创建一个新窗口 + // 注意:这只是示例代码,实际使用时需要根据具体服务API调整 + console.log('组件正在使用注入的服务设置UI...') + } +} + +// 5. 动态获取服务示例 +function dynamicServiceExample(serviceId: string) { + // 使用get方法动态获取服务 + try { + const service = ServiceProvider.getServiceById(serviceId as any) + console.log(`动态获取服务[${serviceId}]:`, !!service) + return service + } catch (error) { + console.error(`无法获取服务[${serviceId}]:`, error) + return null + } +} + +// 导出示例函数供其他文件使用 +export { startApplication, dynamicServiceExample, ApplicationComponent } + +// 注意:在实际应用中,你会在main.ts或应用入口文件中调用startApplication() +// startApplication(); // 取消注释以启动应用 diff --git a/src/services/di/types.d.ts b/src/services/di/types.d.ts new file mode 100644 index 0000000..d16f33b --- /dev/null +++ b/src/services/di/types.d.ts @@ -0,0 +1,91 @@ +import { IServiceContainer } from './IServiceContainer' +import { ServiceIds } from './ServiceRegistry' + +/** + * 定义所有服务类型映射 + * 这个接口用于在ServiceProvider中提供强类型的服务访问 + */ +export interface ServiceTypeMap { + [ServiceIds.RESOURCE_SERVICE]: any // ResourceService + [ServiceIds.WINDOW_FORM_SERVICE]: any // WindowFormService + [ServiceIds.SANDBOX_ENGINE]: any // ApplicationSandboxEngine + [ServiceIds.LIFECYCLE_MANAGER]: any // ApplicationLifecycleManager + [ServiceIds.SYSTEM_SERVICE]: any // SystemServiceIntegration + [ServiceIds.EVENT_BUILDER]: any // IEventBuilder + [ServiceIds.EXTERNAL_APP_DISCOVERY]: any // 外部应用发现服务 + [ServiceIds.ERROR_HANDLER]: any // 错误处理服务 +} + +/** + * 扩展IServiceContainer接口,提供强类型的get方法 + */ +declare module './IServiceContainer' { + export interface IServiceContainer { + /** + * 获取服务实例(带类型支持) + * @param id 服务ID + * @returns 服务实例,类型根据服务ID自动推断 + */ + getService(id: T): ServiceTypeMap[T] + } +} + +/** + * 扩展ServiceProvider类的静态方法类型 + */ +declare module './ServiceProvider' { + // 仅扩展现有ServiceProvider类,不重新声明 + interface ServiceProvider { + /** + * 获取服务实例(带类型支持) + * @param id 服务ID + * @returns 服务实例,类型根据服务ID自动推断 + */ + static getService(id: T): ServiceTypeMap[T] + + /** + * 获取资源服务 + */ + static getResourceService(): ServiceTypeMap[typeof ServiceIds.RESOURCE_SERVICE] + + /** + * 获取窗口表单服务 + */ + static getWindowFormService(): ServiceTypeMap[typeof ServiceIds.WINDOW_FORM_SERVICE] + + /** + * 获取沙箱引擎 + */ + static getSandboxEngine(): ServiceTypeMap[typeof ServiceIds.SANDBOX_ENGINE] + + /** + * 获取生命周期管理器 + */ + static getLifecycleManager(): ServiceTypeMap[typeof ServiceIds.LIFECYCLE_MANAGER] + + /** + * 获取系统服务 + */ + static getSystemService(): ServiceTypeMap[typeof ServiceIds.SYSTEM_SERVICE] + + /** + * 获取事件构建器 + */ + static getEventBuilder(): ServiceTypeMap[typeof ServiceIds.EVENT_BUILDER] + + /** + * 获取外部应用发现服务 + */ + static getExternalAppDiscovery(): ServiceTypeMap[typeof ServiceIds.EXTERNAL_APP_DISCOVERY] + + /** + * 获取错误处理服务 + */ + static getErrorHandler(): ServiceTypeMap[typeof ServiceIds.ERROR_HANDLER] + } +} + +/** + * 声明Inject装饰器类型 + */ +declare function Inject(serviceId: T): PropertyDecorator