@@ -56,6 +56,20 @@ export class ServiceContainer {
5656 private registrations = new Map < InjectionToken , Registration > ( ) ;
5757 private resolutionStack = new Set < InjectionToken > ( ) ; // 循环依赖检测
5858 private disposables : Array < { instance : any ; method : string | symbol } > = [ ] ;
59+ private parent ?: ServiceContainer ;
60+
61+ /**
62+ * 创建子作用域容器
63+ *
64+ * 子容器自动继承父容器的所有注册:resolve 时先查本地,本地没有则回退到父容器。
65+ * 子容器可以 register 同名 token 来覆盖父容器的服务。
66+ * dispose() 只清理子容器自身创建的实例,不影响父容器。
67+ */
68+ createScope ( ) : ServiceContainer {
69+ const child = new ServiceContainer ( ) ;
70+ child . parent = this ;
71+ return child ;
72+ }
5973
6074 /**
6175 * 注册服务
@@ -251,7 +265,7 @@ export class ServiceContainer {
251265 // 2. 查找注册信息
252266 let registration = this . registrations . get ( token ) ;
253267
254- // 3. 如果没有注册,且是带装饰器的类,则自动注册
268+ // 3. 如果没有注册,且是带装饰器的类,则自动注册(注册到本地)
255269 if ( ! registration && typeof token === "function" ) {
256270 if ( isInjectable ( token ) ) {
257271 const lifecycle = getLifecycle ( token ) ?? Lifecycle . Transient ;
@@ -260,6 +274,11 @@ export class ServiceContainer {
260274 }
261275 }
262276
277+ // 4. 本地无注册,委托父容器
278+ if ( ! registration && this . parent ) {
279+ return this . parent . resolve < T > ( token ) ;
280+ }
281+
263282 if ( ! registration ) {
264283 const tokenStr = tokenToString ( token ) ;
265284 const hint = typeof token === "function"
@@ -308,9 +327,8 @@ export class ServiceContainer {
308327 */
309328 isRegistered < T > ( token : InjectionToken < T > ) : boolean {
310329 if ( this . registrations . has ( token ) ) return true ;
311- // 检查是否是带装饰器的类(可以自动注册)
312330 if ( typeof token === "function" && isInjectable ( token ) ) return true ;
313- return false ;
331+ return this . parent ?. isRegistered ( token ) ?? false ;
314332 }
315333
316334 /**
0 commit comments