* 解析服务 * * @param identifier - 服务标识符(构造函数或 Symbol) * @returns 服务实例 * @throws 如果服务未注册或存在循环依赖 * * @example * ```typescript * const timer = container.resolve(TimerManager); * * // 使用 Symbol * const fileSystem = container.resolve(IFileSystem);
(identifier: ServiceIdentifier<T>)
| 255 | * ``` |
| 256 | */ |
| 257 | public resolve<T extends IService>(identifier: ServiceIdentifier<T>): T { |
| 258 | const registration = this._services.get(identifier); |
| 259 | const name = typeof identifier === 'symbol' ? identifier.description : identifier.name; |
| 260 | |
| 261 | if (!registration) { |
| 262 | throw new Error(`Service ${name} is not registered`); |
| 263 | } |
| 264 | |
| 265 | // 检测循环依赖 |
| 266 | if (this._resolving.has(identifier)) { |
| 267 | const chain = Array.from(this._resolving).map((t) => |
| 268 | typeof t === 'symbol' ? t.description : t.name |
| 269 | ).join(' -> '); |
| 270 | throw new Error(`Circular dependency detected: ${chain} -> ${name}`); |
| 271 | } |
| 272 | |
| 273 | // 如果是单例且已经有实例,直接返回 |
| 274 | if (registration.lifetime === ServiceLifetime.Singleton && registration.instance) { |
| 275 | return registration.instance as T; |
| 276 | } |
| 277 | |
| 278 | // 添加到解析栈 |
| 279 | this._resolving.add(identifier); |
| 280 | |
| 281 | try { |
| 282 | // 创建实例 |
| 283 | let instance: IService; |
| 284 | |
| 285 | if (registration.factory) { |
| 286 | // 使用工厂函数 |
| 287 | instance = registration.factory(this); |
| 288 | } else if (registration.type) { |
| 289 | // 直接构造 |
| 290 | instance = new (registration.type)(); |
| 291 | } else { |
| 292 | throw new Error(`Service ${name} has no factory or type to construct`); |
| 293 | } |
| 294 | |
| 295 | // 如果是单例,缓存实例 |
| 296 | if (registration.lifetime === ServiceLifetime.Singleton) { |
| 297 | registration.instance = instance; |
| 298 | |
| 299 | // 如果使用了@Updatable装饰器,添加到可更新列表 |
| 300 | if (registration.type && checkUpdatable(registration.type)) { |
| 301 | const metadata = getUpdatableMetadata(registration.type); |
| 302 | const priority = metadata?.priority ?? 0; |
| 303 | this._updatableServices.push({ instance, priority }); |
| 304 | |
| 305 | // 按优先级排序(数值越小越先执行) |
| 306 | this._updatableServices.sort((a, b) => a.priority - b.priority); |
| 307 | |
| 308 | logger.debug(`Service ${name} is updatable (priority: ${priority}), added to update list`); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | return instance as T; |
| 313 | } finally { |
| 314 | // 从解析栈移除 |