using System; using System.Collections.Generic; namespace Core { /// /// Locator 基类,支持父级查找机制。 /// public abstract class ServiceLocatorBase { protected readonly Dictionary _services = new(); /// 父 Locator,用于层级查找。 public ServiceLocatorBase Parent { get; set; } /// /// 注册一个服务实例。 /// public virtual void Register(T service) { _services[typeof(T)] = service; OnServiceRegistered?.Invoke(typeof(T), service); } /// /// 注销一个服务。 /// public virtual void Unregister(T service) { if (_services.TryGetValue(typeof(T), out var instance) && instance.Equals(service)) _services.Remove(typeof(T)); } /// /// 解析服务(支持向父级递归查找)。 /// public virtual T Resolve() { if (_services.TryGetValue(typeof(T), out var instance)) return (T)instance; return Parent != null ? Parent.Resolve() : default; } /// 清空所有服务。 public virtual void Clear() => _services.Clear(); /// 服务注册事件:当某个服务注册时触发。 public event Action OnServiceRegistered; /// /// 尝试立即获取服务。 /// public virtual bool TryGet(out T service) { if (_services.TryGetValue(typeof(T), out var instance)) { service = (T)instance; return true; } else if (Parent != null) { return Parent.TryGet(out service); } service = default; return false; } /// /// 尝试获取服务;若不存在,则等待其注册。 /// public virtual bool TryGetWait(Action onGet) { if (TryGet(out var service)) { onGet?.Invoke(service); return true; } void Handler(Type type, object instance) { if (type == typeof(T)) { onGet?.Invoke((T)instance); OnServiceRegistered -= Handler; } } OnServiceRegistered += Handler; return false; } } /// /// 泛型单例版本的 Locator。 /// public abstract class ServiceLocator : ServiceLocatorBase where T : ServiceLocator, new() { private static readonly Lazy _instance = new(() => new T()); /// 全局访问入口。 public static T Instance => _instance.Value; } }