| 105 | * ``` |
| 106 | */ |
| 107 | export class ServiceContainer { |
| 108 | /** |
| 109 | * 服务注册表 |
| 110 | */ |
| 111 | private _services: Map<ServiceIdentifier, ServiceRegistration<IService>> = new Map(); |
| 112 | |
| 113 | /** |
| 114 | * 正在解析的服务栈(用于循环依赖检测) |
| 115 | */ |
| 116 | private _resolving: Set<ServiceIdentifier> = new Set(); |
| 117 | |
| 118 | /** |
| 119 | * 可更新的服务列表 |
| 120 | * |
| 121 | * 自动收集所有使用@Updatable装饰器标记的服务,供Core统一更新 |
| 122 | * 按优先级排序(数值越小越先执行) |
| 123 | */ |
| 124 | private _updatableServices: Array<{ instance: IService; priority: number }> = []; |
| 125 | |
| 126 | /** |
| 127 | * 注册单例服务 |
| 128 | * |
| 129 | * @param type - 服务类型 |
| 130 | * @param factory - 可选的工厂函数 |
| 131 | * |
| 132 | * @example |
| 133 | * ```typescript |
| 134 | * // 直接注册类型 |
| 135 | * container.registerSingleton(TimerManager); |
| 136 | * |
| 137 | * // 使用工厂函数 |
| 138 | * container.registerSingleton(Logger, (c) => { |
| 139 | * return createLogger('App'); |
| 140 | * }); |
| 141 | * ``` |
| 142 | */ |
| 143 | public registerSingleton<T extends IService>( |
| 144 | type: ServiceType<T>, |
| 145 | factory?: (container: ServiceContainer) => T |
| 146 | ): void { |
| 147 | if (this._services.has(type as ServiceIdentifier)) { |
| 148 | logger.warn(`Service ${type.name} is already registered`); |
| 149 | return; |
| 150 | } |
| 151 | |
| 152 | this._services.set(type as ServiceIdentifier, { |
| 153 | identifier: type as ServiceIdentifier, |
| 154 | type: type as ServiceType<IService>, |
| 155 | ...(factory && { factory: factory as (container: ServiceContainer) => IService }), |
| 156 | lifetime: ServiceLifetime.Singleton |
| 157 | }); |
| 158 | |
| 159 | logger.debug(`Registered singleton service: ${type.name}`); |
| 160 | } |
| 161 | |
| 162 | /** |
| 163 | * 注册瞬时服务 |
| 164 | * |
nothing calls this directly
no outgoing calls
no test coverage detected