using System; using System.Collections.Generic; using System.Linq; using asap.core; using UnityEngine; namespace Activity { /// /// 活动Scope生命周期管理器 /// 负责管理每个活动ID独立的DI容器Scope /// public class ActivityScopeManager : IDisposable { private readonly Dictionary<(int,int),Container.IScope> _activityScopes = new(); private readonly Dictionary _activeRegistry = new(); /// /// 销毁所有Scope /// public void Dispose() { foreach (var scopesValue in _activityScopes.Values) scopesValue?.Dispose(); _activityScopes.Clear(); _activeRegistry.Clear(); Debug.Log("[ActivityScopeManager] Disposed all activity scopes"); } /// /// 为指定活动ID创建Scope /// public Container.IScope CreateActivityScope((int type,int subtype) typeKey) { if (_activityScopes.TryGetValue(typeKey, out var activityScope)) { Debug.LogWarning($"[ActivityScopeManager] Activity scope for activity {typeKey} already exists"); return activityScope; } var scope = GContext.container.CreateScope(); if (scope == null) { Debug.LogError($"[ActivityScopeManager] Failed to create scope for activity {typeKey}"); return null; } _activityScopes.Add(typeKey, scope); return scope; } /// /// 获取指定活动ID的Scope,如果不存在则创建 /// public Container.IScope GetActivityScope((int type,int subtype) typeKey) { if (_activityScopes.TryGetValue(typeKey, out var scope)) return scope; scope = CreateActivityScope(typeKey); return scope; } /// /// 销毁指定活动ID的Scope /// public void DestroyActivityScope((int type,int subtype) typeKey) { if (!_activityScopes.TryGetValue(typeKey, out var scope)) return; scope.Dispose(); _activityScopes.Remove(typeKey); // 清理所有指向该 typeKey 的注册项,避免 Resolve() 取到已销毁 Scope 的 typeKey var keysToRemove = _activeRegistry .Where(x => x.Value == typeKey) .Select(x => x.Key) .ToList(); foreach (var key in keysToRemove) _activeRegistry.Remove(key); Debug.Log($"[ActivityScopeManager] Destroyed scope for activity {typeKey}, registry entries removed: {keysToRemove.Count}"); } /// /// 检查指定活动ID是否有活跃的Scope /// public bool HasActiveScope((int type,int subtype) typeKey) { return _activityScopes.ContainsKey(typeKey); } /// /// 检查类型是否已注册 /// public bool IsRegistered() where TM : AEventDataManager { return _activeRegistry.ContainsKey(typeof(TM)); } /// /// 获取或注册实例 /// public TM GetOrRegisterInstance((int type, int subtype) typeKey) where TM : AEventDataManager { var scope = GetActivityScope(typeKey); if (scope == null) return null; // 如果未注册,先注册到 GContext.container if (!_activeRegistry.ContainsKey(typeof(TM))) { GContext.container.Register(typeof(TM).Name).PerScope(); _activeRegistry.Add(typeof(TM), typeKey); } return scope.GetInstance((typeof(TM), typeof(TM).Name)) as TM; } /// /// 根据 TM 类型获取已注册的 typeKey /// public (int EventType, int EventSubType)? GetRegisteredTypeKey() where TM : AEventDataManager { if (_activeRegistry.TryGetValue(typeof(TM), out var typeKey)) return typeKey; return null; } } }