From d8df348bec2c179bd343b09f9b69c1d337faaf97 Mon Sep 17 00:00:00 2001 From: GeWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Sat, 17 Jan 2026 09:14:04 +0800 Subject: [PATCH] =?UTF-8?q?refactor(architecture):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E6=9E=B6=E6=9E=84=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=92=8C=E7=BB=84=E4=BB=B6=E6=B3=A8=E5=86=8C=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加IDisposable接口导入并优化组件生命周期管理 - 引入IInitializable和IDisposable统一管理待初始化和可销毁组件 - 实现统一的组件生命周期注册逻辑RegisterLifecycleComponent方法 - 重构InitializeAllComponentsAsync方法按类型分组初始化组件 - 更新RegisterSystem、RegisterModel和RegisterUtility方法使用新生命周期管理 - 修改Destroy方法使用新的_disposables集合进行有序销毁 - 移除旧的_mModels、_mSystems、_mContextUtilities字段 - 添加ValidateRegistration方法验证注册时机 - 重构InitializeInternalAsync方法使用新的组件初始化流程 - 移除废弃的InitializeComponentAsync方法 - 添加异常处理和错误日志记录机制 --- GFramework.Core/architecture/Architecture.cs | 502 ++++++++++--------- 1 file changed, 266 insertions(+), 236 deletions(-) diff --git a/GFramework.Core/architecture/Architecture.cs b/GFramework.Core/architecture/Architecture.cs index 13e709b..d66498e 100644 --- a/GFramework.Core/architecture/Architecture.cs +++ b/GFramework.Core/architecture/Architecture.cs @@ -4,6 +4,7 @@ using GFramework.Core.Abstractions.enums; using GFramework.Core.Abstractions.environment; using GFramework.Core.Abstractions.events; using GFramework.Core.Abstractions.ioc; +using GFramework.Core.Abstractions.lifecycle; using GFramework.Core.Abstractions.logging; using GFramework.Core.Abstractions.model; using GFramework.Core.Abstractions.query; @@ -13,6 +14,7 @@ using GFramework.Core.environment; using GFramework.Core.events; using GFramework.Core.extensions; using GFramework.Core.logging; +using IDisposable = GFramework.Core.Abstractions.lifecycle.IDisposable; namespace GFramework.Core.architecture; @@ -28,45 +30,6 @@ public abstract class Architecture( ) : IArchitecture { - /// - /// 获取架构配置对象 - /// - /// - /// 返回一个IArchitectureConfiguration接口的实例,默认为DefaultArchitectureConfiguration类型 - /// - private IArchitectureConfiguration Configuration { get; } = configuration ?? new ArchitectureConfiguration(); - - /// - /// 获取环境配置对象 - /// - /// - /// 返回一个IEnvironment接口的实例,默认为DefaultEnvironment类型 - /// - private IEnvironment Environment { get; } = environment ?? new DefaultEnvironment(); - - - /// - /// 获取架构服务对象 - /// - /// - /// 返回一个IArchitectureServices接口的实例,默认为DefaultArchitectureServices类型 - /// - private IArchitectureServices Services { get; } = services ?? new ArchitectureServices(); - - /// - /// 获取依赖注入容器 - /// - /// - /// 通过Services属性获取的IArchitectureServices中的Container属性 - /// - private IIocContainer Container => Services.Container; - - private IEventBus EventBus => Services.EventBus; - - private ICommandBus CommandBus => Services.CommandBus; - - private IQueryBus QueryBus => Services.QueryBus; - #region Module Management /// @@ -76,8 +39,7 @@ public abstract class Architecture( public void InstallModule(IArchitectureModule module) { var name = module.GetType().Name; - var logger = - LoggerFactoryResolver.Provider.CreateLogger(name); + var logger = LoggerFactoryResolver.Provider.CreateLogger(name); logger.Debug($"Installing module: {name}"); RegisterLifecycleHook(module); Container.RegisterPlurality(module); @@ -87,38 +49,42 @@ public abstract class Architecture( #endregion - #region Fields and Properties + #region Properties /// - /// 存储尚未初始化的模型集合,在初始化阶段统一调用Init方法 + /// 获取架构配置对象 /// - private readonly HashSet _mModels = []; + private IArchitectureConfiguration Configuration { get; } = configuration ?? new ArchitectureConfiguration(); /// - /// 存储尚未初始化的系统集合,在初始化阶段统一调用Init方法 + /// 获取环境配置对象 /// - private readonly HashSet _mSystems = []; + private IEnvironment Environment { get; } = environment ?? new DefaultEnvironment(); /// - /// 存储所有已注册的系统,用于销毁 + /// 获取架构服务对象 /// - private readonly HashSet _allSystems = []; + private IArchitectureServices Services { get; } = services ?? new ArchitectureServices(); /// - /// 存储尚未初始化的上下文工具集合 + /// 获取依赖注入容器 /// - private readonly HashSet _mContextUtilities = []; - + private IIocContainer Container => Services.Container; /// - /// 标记架构是否已初始化完成 + /// 获取事件总线 /// - private bool _mInitialized; + private IEventBus EventBus => Services.EventBus; /// - /// 生命周期感知对象列表 + /// 获取命令总线 /// - private readonly List _lifecycleHooks = []; + private ICommandBus CommandBus => Services.CommandBus; + + /// + /// 获取查询总线 + /// + private IQueryBus QueryBus => Services.QueryBus; /// /// 当前架构的阶段 @@ -126,14 +92,44 @@ public abstract class Architecture( public ArchitecturePhase CurrentPhase { get; private set; } /// - /// 日志记录器实例,用于记录应用程序的运行日志 + /// 架构上下文 + /// + public IArchitectureContext Context => _context!; + + #endregion + + #region Fields + + /// + /// 存储所有待初始化的组件(统一管理) + /// + private readonly HashSet _pendingInitializableList = []; + + /// + /// 存储所有需要销毁的组件(统一管理) + /// + private readonly HashSet _disposables = []; + + /// + /// 生命周期感知对象列表 + /// + private readonly List _lifecycleHooks = []; + + /// + /// 标记架构是否已初始化完成 + /// + private bool _mInitialized; + + /// + /// 日志记录器实例 /// private ILogger _logger = null!; + /// + /// 架构上下文实例 + /// private IArchitectureContext? _context = context; - public IArchitectureContext Context => _context!; - #endregion #region Lifecycle Management @@ -158,7 +154,8 @@ public abstract class Architecture( var previousPhase = CurrentPhase; CurrentPhase = next; - if (previousPhase != next) _logger.Info($"Architecture phase changed: {previousPhase} -> {next}"); + if (previousPhase != next) + _logger.Info($"Architecture phase changed: {previousPhase} -> {next}"); NotifyPhase(next); @@ -195,6 +192,114 @@ public abstract class Architecture( _lifecycleHooks.Add(hook); } + /// + /// 统一的组件生命周期注册逻辑 + /// + /// 要注册的组件 + private void RegisterLifecycleComponent(T component) + { + // 处理初始化 + if (component is IInitializable initializable) + { + if (!_mInitialized) + { + _pendingInitializableList.Add(initializable); + _logger.Trace($"Added {component.GetType().Name} to pending initialization queue"); + } + else + { + throw new InvalidOperationException( + "Cannot initialize component after Architecture is Ready"); + } + } + + // 处理销毁 + if (component is not IDisposable disposable) return; + _disposables.Add(disposable); + _logger.Trace($"Registered {component.GetType().Name} for destruction"); + } + + /// + /// 初始化所有待初始化的组件 + /// + /// 是否使用异步模式 + private async Task InitializeAllComponentsAsync(bool asyncMode) + { + _logger.Info($"Initializing {_pendingInitializableList.Count} components"); + + // 按类型分组初始化(保持原有的阶段划分) + var utilities = _pendingInitializableList.OfType().ToList(); + var models = _pendingInitializableList.OfType().ToList(); + var systems = _pendingInitializableList.OfType().ToList(); + + // 1. 初始化工具 + if (utilities.Count != 0) + { + EnterPhase(ArchitecturePhase.BeforeUtilityInit); + _logger.Info($"Initializing {utilities.Count} context utilities"); + + foreach (var utility in utilities) + { + _logger.Debug($"Initializing utility: {utility.GetType().Name}"); + await InitializeComponentAsync(utility, asyncMode); + } + + EnterPhase(ArchitecturePhase.AfterUtilityInit); + _logger.Info("All context utilities initialized"); + } + + // 2. 初始化模型 + if (models.Count != 0) + { + EnterPhase(ArchitecturePhase.BeforeModelInit); + _logger.Info($"Initializing {models.Count} models"); + + foreach (var model in models) + { + _logger.Debug($"Initializing model: {model.GetType().Name}"); + await InitializeComponentAsync(model, asyncMode); + } + + EnterPhase(ArchitecturePhase.AfterModelInit); + _logger.Info("All models initialized"); + } + + // 3. 初始化系统 + if (systems.Count != 0) + { + EnterPhase(ArchitecturePhase.BeforeSystemInit); + _logger.Info($"Initializing {systems.Count} systems"); + + foreach (var system in systems) + { + _logger.Debug($"Initializing system: {system.GetType().Name}"); + await InitializeComponentAsync(system, asyncMode); + } + + EnterPhase(ArchitecturePhase.AfterSystemInit); + _logger.Info("All systems initialized"); + } + + _pendingInitializableList.Clear(); + _logger.Info("All components initialized"); + } + + /// + /// 异步初始化单个组件 + /// + /// 要初始化的组件 + /// 是否使用异步模式 + private static async Task InitializeComponentAsync(IInitializable component, bool asyncMode) + { + if (asyncMode && component is IAsyncInitializable asyncInit) + { + await asyncInit.InitializeAsync(); + } + else + { + component.Init(); + } + } /// /// 抽象初始化方法,由子类重写以进行自定义初始化操作 @@ -202,12 +307,8 @@ public abstract class Architecture( protected abstract void Init(); /// - /// 销毁架构并清理所有系统资源 + /// 销毁架构并清理所有组件资源 /// - /// - /// 此函数负责有序地销毁架构中的所有系统组件,并发送相应的生命周期事件。 - /// 函数会确保只执行一次销毁操作,避免重复销毁。 - /// public virtual void Destroy() { // 检查当前阶段,如果已经处于销毁或已销毁状态则直接返回 @@ -222,15 +323,24 @@ public abstract class Architecture( EnterPhase(ArchitecturePhase.Destroying); EventBus.Send(new ArchitectureEvents.ArchitectureDestroyingEvent()); - // 销毁所有系统组件并清空系统列表 - _logger.Info($"Destroying {_allSystems.Count} systems"); - foreach (var system in _allSystems) + // 销毁所有实现了 IDisposable 的组件 + _logger.Info($"Destroying {_disposables.Count} disposable components"); + + foreach (var disposable in _disposables) { - _logger.Debug($"Destroying system: {system.GetType().Name}"); - system.Destroy(); + try + { + _logger.Debug($"Destroying component: {disposable.GetType().Name}"); + disposable.Destroy(); + } + catch (Exception ex) + { + _logger.Error($"Error destroying {disposable.GetType().Name}", ex); + // 继续销毁其他组件,不会因为一个组件失败而中断 + } } - _allSystems.Clear(); + _disposables.Clear(); // 进入已销毁阶段并发送销毁完成事件 EnterPhase(ArchitecturePhase.Destroyed); @@ -242,6 +352,87 @@ public abstract class Architecture( #region Component Registration + /// + /// 验证是否允许注册组件 + /// + /// 组件类型描述 + /// 当不允许注册时抛出 + private void ValidateRegistration(string componentType) + { + if (CurrentPhase < ArchitecturePhase.Ready || + Configuration.ArchitectureProperties.AllowLateRegistration) return; + var errorMsg = $"Cannot register {componentType} after Architecture is Ready"; + _logger.Error(errorMsg); + throw new InvalidOperationException(errorMsg); + } + + /// + /// 注册一个系统到架构中。 + /// 若当前未初始化,则暂存至待初始化列表;否则立即初始化该系统。 + /// + /// 要注册的系统类型 + /// 要注册的系统实例 + public void RegisterSystem(TSystem system) where TSystem : ISystem + { + ValidateRegistration("system"); + + _logger.Debug($"Registering system: {typeof(TSystem).Name}"); + + system.SetContext(Context); + Container.RegisterPlurality(system); + + // 处理生命周期 + RegisterLifecycleComponent(system); + + _logger.Info($"System registered: {typeof(TSystem).Name}"); + } + + /// + /// 注册一个模型到架构中。 + /// 若当前未初始化,则暂存至待初始化列表;否则立即初始化该模型。 + /// + /// 要注册的模型类型 + /// 要注册的模型实例 + public void RegisterModel(TModel model) where TModel : IModel + { + ValidateRegistration("model"); + + _logger.Debug($"Registering model: {typeof(TModel).Name}"); + + model.SetContext(Context); + Container.RegisterPlurality(model); + + // 处理生命周期 + RegisterLifecycleComponent(model); + + _logger.Info($"Model registered: {typeof(TModel).Name}"); + } + + /// + /// 注册一个工具到架构中。 + /// 工具不会被延迟初始化,直接放入IOC容器供后续使用。 + /// + /// 要注册的工具类型 + /// 要注册的工具实例 + public void RegisterUtility(TUtility utility) where TUtility : IUtility + { + _logger.Debug($"Registering utility: {typeof(TUtility).Name}"); + + utility.IfType(contextUtility => + { + contextUtility.SetContext(Context); + // 处理生命周期 + RegisterLifecycleComponent(contextUtility); + }); + + Container.RegisterPlurality(utility); + _logger.Info($"Utility registered: {typeof(TUtility).Name}"); + } + + #endregion + + #region Initialization + /// /// 同步初始化方法,阻塞当前线程直到初始化完成 /// @@ -255,8 +446,8 @@ public abstract class Architecture( { _logger.Error("Architecture initialization failed:", e); EnterPhase(ArchitecturePhase.FailedInitialization); - // 发送初始化失败事件 EventBus.Send(new ArchitectureEvents.ArchitectureFailedInitializationEvent()); + throw; } } @@ -274,34 +465,11 @@ public abstract class Architecture( { _logger.Error("Architecture initialization failed:", e); EnterPhase(ArchitecturePhase.FailedInitialization); - // 发送初始化失败事件 EventBus.Send(new ArchitectureEvents.ArchitectureFailedInitializationEvent()); + throw; } } - /// - /// 异步初始化组件 - /// - /// 要初始化的组件对象 - /// 是否启用异步模式 - /// 表示异步操作的任务 - private static async Task InitializeComponentAsync(object component, bool asyncMode) - { - // 根据组件类型和异步模式选择相应的初始化方法 - if (asyncMode && component is IAsyncInitializable asyncInit) - await asyncInit.InitializeAsync(); - else - switch (component) - { - case IModel model: - model.Init(); - break; - case ISystem system: - system.Init(); - break; - } - } - /// /// 异步初始化架构内部组件,包括上下文、模型和系统的初始化 /// @@ -310,72 +478,26 @@ public abstract class Architecture( private async Task InitializeInternalAsync(bool asyncMode) { // === 基础上下文 & Logger === - // 设置日志工厂提供程序 LoggerFactoryResolver.Provider = Configuration.LoggerProperties.LoggerFactoryProvider; - // 创建日志记录器实例 _logger = LoggerFactoryResolver.Provider.CreateLogger(GetType().Name); Environment.Initialize(); + // 初始化架构上下文(如果尚未初始化) _context ??= new ArchitectureContext(Container, EventBus, CommandBus, QueryBus, Environment); - // 将当前架构类型与上下文绑定到游戏上下文 GameContext.Bind(GetType(), _context); // 为服务设置上下文 Services.SetContext(_context); // === 用户 Init === - // 调用子类实现的初始化方法 _logger.Debug("Calling user Init()"); Init(); _logger.Debug("User Init() completed"); - // === Context Utility 初始化阶段 === - EnterPhase(ArchitecturePhase.BeforeUtilityInit); - _logger.Info($"Initializing {_mContextUtilities.Count} context utilities"); - foreach (var utility in _mContextUtilities) - { - _logger.Debug($"Initializing context utility: {utility.GetType().Name}"); - utility.Init(); - } - - _mContextUtilities.Clear(); - EnterPhase(ArchitecturePhase.AfterUtilityInit); - _logger.Info("All context utilities initialized"); - - // === 模型初始化阶段 === - // 在此阶段初始化所有注册的模型组件 - EnterPhase(ArchitecturePhase.BeforeModelInit); - _logger.Info($"Initializing {_mModels.Count} models"); - - // 异步初始化所有已注册但尚未初始化的模型 - foreach (var model in _mModels) - { - _logger.Debug($"Initializing model: {model.GetType().Name}"); - await InitializeComponentAsync(model, asyncMode); - } - - _mModels.Clear(); - EnterPhase(ArchitecturePhase.AfterModelInit); - _logger.Info("All models initialized"); - - // === 系统初始化阶段 === - // 在此阶段初始化所有注册的系统组件 - EnterPhase(ArchitecturePhase.BeforeSystemInit); - _logger.Info($"Initializing {_mSystems.Count} systems"); - - // 异步初始化所有已注册但尚未初始化的系统 - foreach (var system in _mSystems) - { - _logger.Debug($"Initializing system: {system.GetType().Name}"); - await InitializeComponentAsync(system, asyncMode); - } - - _mSystems.Clear(); - EnterPhase(ArchitecturePhase.AfterSystemInit); - _logger.Info("All systems initialized"); + // === 组件初始化阶段 === + await InitializeAllComponentsAsync(asyncMode); // === 初始化完成阶段 === - // 冻结IOC容器并标记架构为就绪状态 Container.Freeze(); _logger.Info("IOC container frozen"); @@ -386,97 +508,5 @@ public abstract class Architecture( _logger.Info($"Architecture {GetType().Name} is ready - all components initialized"); } - - /// - /// 注册一个系统到架构中。 - /// 若当前未初始化,则暂存至待初始化列表;否则立即初始化该系统。 - /// - /// 要注册的系统类型 - /// 要注册的系统实例 - public void RegisterSystem(TSystem system) where TSystem : ISystem - { - if (CurrentPhase >= ArchitecturePhase.Ready && !Configuration.ArchitectureProperties.AllowLateRegistration) - { - const string errorMsg = "Cannot register system after Architecture is Ready"; - _logger.Error(errorMsg); - throw new InvalidOperationException(errorMsg); - } - - _logger.Debug($"Registering system: {typeof(TSystem).Name}"); - system.SetContext(Context); - Container.RegisterPlurality(system); - _allSystems.Add(system); - if (!_mInitialized) - { - _mSystems.Add(system); - } - else - { - _logger.Trace($"Immediately initializing system: {typeof(TSystem).Name}"); - system.Init(); - } - - _logger.Info($"System registered: {typeof(TSystem).Name}"); - } - - /// - /// 注册一个模型到架构中。 - /// 若当前未初始化,则暂存至待初始化列表;否则立即初始化该模型。 - /// - /// 要注册的模型类型 - /// 要注册的模型实例 - public void RegisterModel(TModel model) where TModel : IModel - { - if (CurrentPhase >= ArchitecturePhase.Ready && !Configuration.ArchitectureProperties.AllowLateRegistration) - { - var errorMsg = "Cannot register model after Architecture is Ready"; - _logger.Error(errorMsg); - throw new InvalidOperationException(errorMsg); - } - - _logger.Debug($"Registering model: {typeof(TModel).Name}"); - model.SetContext(Context); - Container.RegisterPlurality(model); - - if (!_mInitialized) - { - _mModels.Add(model); - } - else - { - _logger.Trace($"Immediately initializing model: {typeof(TModel).Name}"); - model.Init(); - } - - _logger.Info($"Model registered: {typeof(TModel).Name}"); - } - - /// - /// 注册一个工具到架构中。 - /// 工具不会被延迟初始化,直接放入IOC容器供后续使用。 - /// - /// 要注册的工具类型 - /// 要注册的工具实例 - public void RegisterUtility(TUtility utility) where TUtility : IUtility - { - _logger.Debug($"Registering utility: {typeof(TUtility).Name}"); - utility.IfType(contextUtility => - { - contextUtility.SetContext(Context); - - if (!_mInitialized) - { - _mContextUtilities.Add(contextUtility); - } - else - { - _logger.Trace($"Immediately initializing context utility: {typeof(TUtility).Name}"); - contextUtility.Init(); - } - }); - Container.RegisterPlurality(utility); - _logger.Info($"Utility registered: {typeof(TUtility).Name}"); - } - #endregion } \ No newline at end of file