| 61 | * ``` |
| 62 | */ |
| 63 | export class ServiceContainer { |
| 64 | private _registrations: Map<ServiceIdentifier, ServiceRegistration> = new Map(); |
| 65 | private _resolving: Set<ServiceIdentifier> = new Set(); |
| 66 | private _disposed: boolean = false; |
| 67 | |
| 68 | /** |
| 69 | * Register a singleton service |
| 70 | * 注册单例服务 |
| 71 | */ |
| 72 | public registerSingleton<T>( |
| 73 | identifier: ServiceIdentifier<T>, |
| 74 | factory: ServiceFactory<T> |
| 75 | ): this { |
| 76 | this.checkDisposed(); |
| 77 | this._registrations.set(identifier, { |
| 78 | factory, |
| 79 | lifecycle: EServiceLifecycle.Singleton |
| 80 | }); |
| 81 | return this; |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * Register a singleton instance directly |
| 86 | * 直接注册单例实例 |
| 87 | */ |
| 88 | public registerInstance<T>(identifier: ServiceIdentifier<T>, instance: T): this { |
| 89 | this.checkDisposed(); |
| 90 | this._registrations.set(identifier, { |
| 91 | factory: () => instance, |
| 92 | lifecycle: EServiceLifecycle.Singleton, |
| 93 | instance |
| 94 | }); |
| 95 | return this; |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Register a transient service (new instance per resolution) |
| 100 | * 注册瞬时服务(每次解析创建新实例) |
| 101 | */ |
| 102 | public registerTransient<T>( |
| 103 | identifier: ServiceIdentifier<T>, |
| 104 | factory: ServiceFactory<T> |
| 105 | ): this { |
| 106 | this.checkDisposed(); |
| 107 | this._registrations.set(identifier, { |
| 108 | factory, |
| 109 | lifecycle: EServiceLifecycle.Transient |
| 110 | }); |
| 111 | return this; |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Resolve a service |
| 116 | * 解析服务 |
| 117 | */ |
| 118 | public resolve<T>(identifier: ServiceIdentifier<T>): T { |
| 119 | this.checkDisposed(); |
| 120 |
nothing calls this directly
no outgoing calls
no test coverage detected