mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-03-22 02:24:30 +08:00
Merge pull request #112 from GeWuYou/refactor/architecture-modular-safety
refactor(architecture): 重构架构类为模块化设计提升代码安全性
This commit is contained in:
commit
27858df94e
@ -41,16 +41,8 @@ public abstract class TestArchitectureBase : Architecture
|
||||
{
|
||||
InitCalled = true;
|
||||
_postRegistrationHook?.Invoke(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 进入指定架构阶段时的处理方法,记录阶段历史
|
||||
/// </summary>
|
||||
/// <param name="next">要进入的下一个架构阶段</param>
|
||||
protected override void EnterPhase(ArchitecturePhase next)
|
||||
{
|
||||
base.EnterPhase(next);
|
||||
// 记录进入的架构阶段到历史列表中
|
||||
PhaseHistory.Add(next);
|
||||
// 订阅阶段变更事件以记录历史
|
||||
PhaseChanged += phase => PhaseHistory.Add(phase);
|
||||
}
|
||||
}
|
||||
@ -1,14 +1,11 @@
|
||||
using GFramework.Core.Abstractions.Architectures;
|
||||
using GFramework.Core.Abstractions.Enums;
|
||||
using GFramework.Core.Abstractions.Environment;
|
||||
using GFramework.Core.Abstractions.Ioc;
|
||||
using GFramework.Core.Abstractions.Lifecycle;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Abstractions.Model;
|
||||
using GFramework.Core.Abstractions.Systems;
|
||||
using GFramework.Core.Abstractions.Utility;
|
||||
using GFramework.Core.Environment;
|
||||
using GFramework.Core.Extensions;
|
||||
using GFramework.Core.Logging;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
@ -17,41 +14,56 @@ namespace GFramework.Core.Architectures;
|
||||
/// <summary>
|
||||
/// 架构基类,提供系统、模型、工具等组件的注册与管理功能。
|
||||
/// 专注于生命周期管理、初始化流程控制和架构阶段转换。
|
||||
///
|
||||
/// 重构说明:此类已重构为协调器模式,将职责委托给专门的管理器:
|
||||
/// - ArchitectureLifecycle: 生命周期管理
|
||||
/// - ArchitectureComponentRegistry: 组件注册管理
|
||||
/// - ArchitectureModules: 模块管理
|
||||
/// </summary>
|
||||
public abstract class Architecture(
|
||||
IArchitectureConfiguration? configuration = null,
|
||||
IEnvironment? environment = null,
|
||||
IArchitectureServices? services = null,
|
||||
IArchitectureContext? context = null
|
||||
)
|
||||
: IArchitecture
|
||||
public abstract class Architecture : IArchitecture
|
||||
{
|
||||
#region Module Management
|
||||
#region Constructor
|
||||
|
||||
/// <summary>
|
||||
/// 注册中介行为管道
|
||||
/// 用于配置Mediator框架的行为拦截和处理逻辑
|
||||
/// 构造函数,初始化架构和管理器
|
||||
/// </summary>
|
||||
/// <typeparam name="TBehavior">行为类型,必须是引用类型</typeparam>
|
||||
public void RegisterMediatorBehavior<TBehavior>() where TBehavior : class
|
||||
/// <param name="configuration">架构配置</param>
|
||||
/// <param name="environment">环境配置</param>
|
||||
/// <param name="services">服务管理器</param>
|
||||
/// <param name="context">架构上下文</param>
|
||||
protected Architecture(
|
||||
IArchitectureConfiguration? configuration = null,
|
||||
IEnvironment? environment = null,
|
||||
IArchitectureServices? services = null,
|
||||
IArchitectureContext? context = null)
|
||||
{
|
||||
_logger.Debug($"Registering mediator behavior: {typeof(TBehavior).Name}");
|
||||
Container.RegisterMediatorBehavior<TBehavior>();
|
||||
Configuration = configuration ?? new ArchitectureConfiguration();
|
||||
Environment = environment ?? new DefaultEnvironment();
|
||||
Services = services ?? new ArchitectureServices();
|
||||
_context = context;
|
||||
|
||||
// 初始化 Logger
|
||||
LoggerFactoryResolver.Provider = Configuration.LoggerProperties.LoggerFactoryProvider;
|
||||
_logger = LoggerFactoryResolver.Provider.CreateLogger(GetType().Name);
|
||||
|
||||
// 初始化管理器
|
||||
_lifecycle = new ArchitectureLifecycle(this, Configuration, Services, _logger);
|
||||
_componentRegistry = new ArchitectureComponentRegistry(this, Configuration, Services, _lifecycle, _logger);
|
||||
_modules = new ArchitectureModules(this, Services, _logger);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Lifecycle Hook Management
|
||||
|
||||
/// <summary>
|
||||
/// 安装架构模块
|
||||
/// 注册生命周期钩子
|
||||
/// </summary>
|
||||
/// <param name="module">要安装的模块</param>
|
||||
/// <returns>安装的模块实例</returns>
|
||||
public IArchitectureModule InstallModule(IArchitectureModule module)
|
||||
/// <param name="hook">生命周期钩子实例</param>
|
||||
/// <returns>注册的钩子实例</returns>
|
||||
public IArchitectureLifecycleHook RegisterLifecycleHook(IArchitectureLifecycleHook hook)
|
||||
{
|
||||
var name = module.GetType().Name;
|
||||
var logger = LoggerFactoryResolver.Provider.CreateLogger(name);
|
||||
logger.Debug($"Installing module: {name}");
|
||||
module.Install(this);
|
||||
logger.Info($"Module installed: {name}");
|
||||
return module;
|
||||
return _lifecycle.RegisterLifecycleHook(hook);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@ -61,361 +73,99 @@ public abstract class Architecture(
|
||||
/// <summary>
|
||||
/// 获取架构配置对象
|
||||
/// </summary>
|
||||
private IArchitectureConfiguration Configuration { get; } = configuration ?? new ArchitectureConfiguration();
|
||||
private IArchitectureConfiguration Configuration { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取环境配置对象
|
||||
/// </summary>
|
||||
private IEnvironment Environment { get; } = environment ?? new DefaultEnvironment();
|
||||
|
||||
private IArchitectureServices Services { get; } = services ?? new ArchitectureServices();
|
||||
private IEnvironment Environment { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取依赖注入容器
|
||||
/// 获取服务管理器
|
||||
/// </summary>
|
||||
private IIocContainer Container => Services.Container;
|
||||
private IArchitectureServices Services { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前架构的阶段
|
||||
/// </summary>
|
||||
public ArchitecturePhase CurrentPhase { get; private set; }
|
||||
public ArchitecturePhase CurrentPhase => _lifecycle.CurrentPhase;
|
||||
|
||||
/// <summary>
|
||||
/// 架构上下文
|
||||
/// </summary>
|
||||
public IArchitectureContext Context => _context!;
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个布尔值,指示当前架构是否处于就绪状态
|
||||
/// </summary>
|
||||
public bool IsReady => _lifecycle.IsReady;
|
||||
|
||||
/// <summary>
|
||||
/// 获取用于配置服务集合的委托
|
||||
/// 默认实现返回null,子类可以重写此属性以提供自定义配置逻辑
|
||||
/// </summary>
|
||||
public virtual Action<IServiceCollection>? Configurator => null;
|
||||
|
||||
/// <summary>
|
||||
/// 阶段变更事件(用于测试和扩展)
|
||||
/// </summary>
|
||||
public event Action<ArchitecturePhase>? PhaseChanged
|
||||
{
|
||||
add => _lifecycle.PhaseChanged += value;
|
||||
remove => _lifecycle.PhaseChanged -= value;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Fields
|
||||
|
||||
private readonly TaskCompletionSource _readyTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个布尔值,指示当前架构是否处于就绪状态。
|
||||
/// 当前架构的阶段等于 ArchitecturePhase.Ready 时返回 true,否则返回 false。
|
||||
/// </summary>
|
||||
public bool IsReady => CurrentPhase == ArchitecturePhase.Ready;
|
||||
|
||||
/// <summary>
|
||||
/// 待初始化组件的去重集合。
|
||||
/// 用于存储需要初始化的组件实例,确保每个组件仅被初始化一次。
|
||||
/// </summary>
|
||||
private readonly HashSet<IInitializable> _pendingInitializableSet = [];
|
||||
|
||||
/// <summary>
|
||||
/// 存储所有待初始化的组件(统一管理,保持注册顺序)
|
||||
/// </summary>
|
||||
private readonly List<IInitializable> _pendingInitializableList = [];
|
||||
|
||||
/// <summary>
|
||||
/// 可销毁组件的去重集合(支持 IDestroyable 和 IAsyncDestroyable)
|
||||
/// </summary>
|
||||
private readonly HashSet<object> _disposableSet = [];
|
||||
|
||||
/// <summary>
|
||||
/// 存储所有需要销毁的组件(统一管理,保持注册逆序销毁)
|
||||
/// </summary>
|
||||
private readonly List<object> _disposables = [];
|
||||
|
||||
/// <summary>
|
||||
/// 生命周期感知对象列表
|
||||
/// </summary>
|
||||
private readonly List<IArchitectureLifecycleHook> _lifecycleHooks = [];
|
||||
|
||||
/// <summary>
|
||||
/// 标记架构是否已初始化完成
|
||||
/// </summary>
|
||||
private bool _mInitialized;
|
||||
|
||||
/// <summary>
|
||||
/// 日志记录器实例
|
||||
/// </summary>
|
||||
private ILogger _logger = null!;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// 架构上下文实例
|
||||
/// </summary>
|
||||
private IArchitectureContext? _context = context;
|
||||
private IArchitectureContext? _context;
|
||||
|
||||
/// <summary>
|
||||
/// 生命周期管理器
|
||||
/// </summary>
|
||||
private readonly ArchitectureLifecycle _lifecycle;
|
||||
|
||||
/// <summary>
|
||||
/// 组件注册管理器
|
||||
/// </summary>
|
||||
private readonly ArchitectureComponentRegistry _componentRegistry;
|
||||
|
||||
/// <summary>
|
||||
/// 模块管理器
|
||||
/// </summary>
|
||||
private readonly ArchitectureModules _modules;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Lifecycle Management
|
||||
#region Module Management
|
||||
|
||||
/// <summary>
|
||||
/// 进入指定的架构阶段,并执行相应的生命周期管理操作
|
||||
/// 注册中介行为管道
|
||||
/// 用于配置Mediator框架的行为拦截和处理逻辑
|
||||
/// </summary>
|
||||
/// <param name="next">要进入的下一个架构阶段</param>
|
||||
/// <exception cref="InvalidOperationException">当阶段转换不被允许时抛出异常</exception>
|
||||
protected virtual void EnterPhase(ArchitecturePhase next)
|
||||
/// <typeparam name="TBehavior">行为类型,必须是引用类型</typeparam>
|
||||
public void RegisterMediatorBehavior<TBehavior>() where TBehavior : class
|
||||
{
|
||||
// 验证阶段转换
|
||||
ValidatePhaseTransition(next);
|
||||
|
||||
// 执行阶段转换
|
||||
var previousPhase = CurrentPhase;
|
||||
CurrentPhase = next;
|
||||
|
||||
if (previousPhase != next)
|
||||
_logger.Info($"Architecture phase changed: {previousPhase} -> {next}");
|
||||
|
||||
// 通知阶段变更
|
||||
NotifyPhase(next);
|
||||
NotifyPhaseAwareObjects(next);
|
||||
_modules.RegisterMediatorBehavior<TBehavior>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证阶段转换是否合法
|
||||
/// 安装架构模块
|
||||
/// </summary>
|
||||
/// <param name="next">目标阶段</param>
|
||||
/// <exception cref="InvalidOperationException">当阶段转换不合法时抛出</exception>
|
||||
private void ValidatePhaseTransition(ArchitecturePhase next)
|
||||
/// <param name="module">要安装的模块</param>
|
||||
/// <returns>安装的模块实例</returns>
|
||||
public IArchitectureModule InstallModule(IArchitectureModule module)
|
||||
{
|
||||
// 不需要严格验证,直接返回
|
||||
if (!Configuration.ArchitectureProperties.StrictPhaseValidation)
|
||||
return;
|
||||
|
||||
// FailedInitialization 可以从任何阶段转换,直接返回
|
||||
if (next == ArchitecturePhase.FailedInitialization)
|
||||
return;
|
||||
|
||||
// 检查转换是否在允许列表中
|
||||
if (ArchitectureConstants.PhaseTransitions.TryGetValue(CurrentPhase, out var allowed) &&
|
||||
allowed.Contains(next))
|
||||
return;
|
||||
|
||||
// 转换不合法,抛出异常
|
||||
var errorMsg = $"Invalid phase transition: {CurrentPhase} -> {next}";
|
||||
_logger.Fatal(errorMsg);
|
||||
throw new InvalidOperationException(errorMsg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通知所有架构阶段感知对象阶段变更
|
||||
/// </summary>
|
||||
/// <param name="phase">新阶段</param>
|
||||
private void NotifyPhaseAwareObjects(ArchitecturePhase phase)
|
||||
{
|
||||
foreach (var obj in Container.GetAll<IArchitecturePhaseListener>())
|
||||
{
|
||||
_logger.Trace($"Notifying phase-aware object {obj.GetType().Name} of phase change to {phase}");
|
||||
obj.OnArchitecturePhase(phase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通知所有生命周期钩子当前阶段变更
|
||||
/// </summary>
|
||||
/// <param name="phase">当前架构阶段</param>
|
||||
private void NotifyPhase(ArchitecturePhase phase)
|
||||
{
|
||||
foreach (var hook in _lifecycleHooks)
|
||||
{
|
||||
hook.OnPhase(phase, this);
|
||||
_logger.Trace($"Notifying lifecycle hook {hook.GetType().Name} of phase {phase}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册生命周期钩子
|
||||
/// </summary>
|
||||
/// <param name="hook">生命周期钩子实例</param>
|
||||
/// <returns>注册的钩子实例</returns>
|
||||
public IArchitectureLifecycleHook RegisterLifecycleHook(IArchitectureLifecycleHook hook)
|
||||
{
|
||||
if (CurrentPhase >= ArchitecturePhase.Ready && !Configuration.ArchitectureProperties.AllowLateRegistration)
|
||||
throw new InvalidOperationException(
|
||||
"Cannot register lifecycle hook after architecture is Ready");
|
||||
_lifecycleHooks.Add(hook);
|
||||
return hook;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 统一的组件生命周期注册逻辑
|
||||
/// </summary>
|
||||
/// <param name="component">要注册的组件</param>
|
||||
private void RegisterLifecycleComponent<T>(T component)
|
||||
{
|
||||
// 处理初始化
|
||||
if (component is IInitializable initializable)
|
||||
{
|
||||
if (!_mInitialized)
|
||||
{
|
||||
// 原子去重:HashSet.Add 返回 true 表示添加成功(之前不存在)
|
||||
if (_pendingInitializableSet.Add(initializable))
|
||||
{
|
||||
_pendingInitializableList.Add(initializable);
|
||||
_logger.Trace($"Added {component.GetType().Name} to pending initialization queue");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Cannot initialize component after Architecture is Ready");
|
||||
}
|
||||
}
|
||||
|
||||
// 处理销毁(支持 IDestroyable 或 IAsyncDestroyable)
|
||||
if (component is not (IDestroyable or IAsyncDestroyable)) return;
|
||||
// 原子去重:HashSet.Add 返回 true 表示添加成功(之前不存在)
|
||||
if (!_disposableSet.Add(component)) return;
|
||||
_disposables.Add(component);
|
||||
_logger.Trace($"Registered {component.GetType().Name} for destruction");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化所有待初始化的组件
|
||||
/// </summary>
|
||||
/// <param name="asyncMode">是否使用异步模式</param>
|
||||
private async Task InitializeAllComponentsAsync(bool asyncMode)
|
||||
{
|
||||
_logger.Info($"Initializing {_pendingInitializableList.Count} components");
|
||||
|
||||
// 按类型分组初始化(保持原有的阶段划分)
|
||||
var utilities = _pendingInitializableList.OfType<IContextUtility>().ToList();
|
||||
var models = _pendingInitializableList.OfType<IModel>().ToList();
|
||||
var systems = _pendingInitializableList.OfType<ISystem>().ToList();
|
||||
|
||||
// 1. 工具初始化阶段(始终进入阶段,仅在有组件时执行初始化)
|
||||
EnterPhase(ArchitecturePhase.BeforeUtilityInit);
|
||||
|
||||
if (utilities.Count != 0)
|
||||
{
|
||||
_logger.Info($"Initializing {utilities.Count} context utilities");
|
||||
|
||||
foreach (var utility in utilities)
|
||||
{
|
||||
_logger.Debug($"Initializing utility: {utility.GetType().Name}");
|
||||
await InitializeComponentAsync(utility, asyncMode);
|
||||
}
|
||||
|
||||
_logger.Info("All context utilities initialized");
|
||||
}
|
||||
|
||||
EnterPhase(ArchitecturePhase.AfterUtilityInit);
|
||||
|
||||
// 2. 模型初始化阶段(始终进入阶段,仅在有组件时执行初始化)
|
||||
EnterPhase(ArchitecturePhase.BeforeModelInit);
|
||||
|
||||
if (models.Count != 0)
|
||||
{
|
||||
_logger.Info($"Initializing {models.Count} models");
|
||||
|
||||
foreach (var model in models)
|
||||
{
|
||||
_logger.Debug($"Initializing model: {model.GetType().Name}");
|
||||
await InitializeComponentAsync(model, asyncMode);
|
||||
}
|
||||
|
||||
_logger.Info("All models initialized");
|
||||
}
|
||||
|
||||
EnterPhase(ArchitecturePhase.AfterModelInit);
|
||||
|
||||
// 3. 系统初始化阶段(始终进入阶段,仅在有组件时执行初始化)
|
||||
EnterPhase(ArchitecturePhase.BeforeSystemInit);
|
||||
|
||||
if (systems.Count != 0)
|
||||
{
|
||||
_logger.Info($"Initializing {systems.Count} systems");
|
||||
|
||||
foreach (var system in systems)
|
||||
{
|
||||
_logger.Debug($"Initializing system: {system.GetType().Name}");
|
||||
await InitializeComponentAsync(system, asyncMode);
|
||||
}
|
||||
|
||||
_logger.Info("All systems initialized");
|
||||
}
|
||||
|
||||
EnterPhase(ArchitecturePhase.AfterSystemInit);
|
||||
|
||||
_pendingInitializableList.Clear();
|
||||
_pendingInitializableSet.Clear();
|
||||
_logger.Info("All components initialized");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步初始化单个组件
|
||||
/// </summary>
|
||||
/// <param name="component">要初始化的组件</param>
|
||||
/// <param name="asyncMode">是否使用异步模式</param>
|
||||
private static async Task InitializeComponentAsync(IInitializable component, bool asyncMode)
|
||||
{
|
||||
if (asyncMode && component is IAsyncInitializable asyncInit)
|
||||
await asyncInit.InitializeAsync();
|
||||
else
|
||||
component.Initialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 抽象初始化方法,由子类重写以进行自定义初始化操作
|
||||
/// </summary>
|
||||
protected abstract void OnInitialize();
|
||||
|
||||
/// <summary>
|
||||
/// 异步销毁架构及所有组件
|
||||
/// </summary>
|
||||
public virtual async ValueTask DestroyAsync()
|
||||
{
|
||||
// 检查当前阶段,如果已经处于销毁或已销毁状态则直接返回
|
||||
if (CurrentPhase >= ArchitecturePhase.Destroying)
|
||||
{
|
||||
_logger.Warn("Architecture destroy called but already in destroying/destroyed state");
|
||||
return;
|
||||
}
|
||||
|
||||
// 进入销毁阶段
|
||||
_logger.Info("Starting architecture destruction");
|
||||
EnterPhase(ArchitecturePhase.Destroying);
|
||||
|
||||
// 销毁所有实现了 IAsyncDestroyable 或 IDestroyable 的组件(按注册逆序销毁)
|
||||
_logger.Info($"Destroying {_disposables.Count} disposable components");
|
||||
|
||||
for (var i = _disposables.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var component = _disposables[i];
|
||||
try
|
||||
{
|
||||
_logger.Debug($"Destroying component: {component.GetType().Name}");
|
||||
|
||||
// 优先使用异步销毁
|
||||
if (component is IAsyncDestroyable asyncDestroyable)
|
||||
{
|
||||
await asyncDestroyable.DestroyAsync();
|
||||
}
|
||||
else if (component is IDestroyable destroyable)
|
||||
{
|
||||
destroyable.Destroy();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error($"Error destroying {component.GetType().Name}", ex);
|
||||
// 继续销毁其他组件,不会因为一个组件失败而中断
|
||||
}
|
||||
}
|
||||
|
||||
_disposables.Clear();
|
||||
_disposableSet.Clear();
|
||||
|
||||
// 销毁服务模块
|
||||
await Services.ModuleManager.DestroyAllAsync();
|
||||
|
||||
Container.Clear();
|
||||
|
||||
// 进入已销毁阶段
|
||||
EnterPhase(ArchitecturePhase.Destroyed);
|
||||
_logger.Info("Architecture destruction completed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁架构并清理所有组件资源(同步方法,保留用于向后兼容)
|
||||
/// </summary>
|
||||
[Obsolete("建议使用 DestroyAsync() 以支持异步清理")]
|
||||
public virtual void Destroy()
|
||||
{
|
||||
DestroyAsync().AsTask().GetAwaiter().GetResult();
|
||||
return _modules.InstallModule(module);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@ -423,177 +173,77 @@ public abstract class Architecture(
|
||||
#region Component Registration
|
||||
|
||||
/// <summary>
|
||||
/// 验证是否允许注册组件
|
||||
/// 注册一个系统到架构中
|
||||
/// </summary>
|
||||
/// <param name="componentType">组件类型描述</param>
|
||||
/// <exception cref="InvalidOperationException">当不允许注册时抛出</exception>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个系统到架构中。
|
||||
/// 若当前未初始化,则暂存至待初始化列表;否则立即初始化该系统。
|
||||
/// </summary>
|
||||
/// <typeparam name="TSystem">要注册的系统类型,必须实现ISystem接口</typeparam>
|
||||
/// <typeparam name="TSystem">要注册的系统类型</typeparam>
|
||||
/// <param name="system">要注册的系统实例</param>
|
||||
/// <returns>注册成功的系统实例</returns>
|
||||
public TSystem RegisterSystem<TSystem>(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}");
|
||||
return system;
|
||||
return _componentRegistry.RegisterSystem(system);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册系统类型,由 DI 容器自动创建实例
|
||||
/// 注册系统类型,由 DI 容器自动创建实例
|
||||
/// </summary>
|
||||
/// <typeparam name="T">系统类型</typeparam>
|
||||
/// <param name="onCreated">可选的实例创建后回调,用于自定义配置</param>
|
||||
/// <param name="onCreated">可选的实例创建后回调</param>
|
||||
public void RegisterSystem<T>(Action<T>? onCreated = null) where T : class, ISystem
|
||||
{
|
||||
ValidateRegistration("system");
|
||||
_logger.Debug($"Registering system type: {typeof(T).Name}");
|
||||
|
||||
Container.RegisterFactory<T>(sp =>
|
||||
{
|
||||
// 1. DI 创建实例
|
||||
var system = ActivatorUtilities.CreateInstance<T>(sp);
|
||||
|
||||
// 2. 框架默认处理
|
||||
system.SetContext(Context);
|
||||
RegisterLifecycleComponent(system);
|
||||
|
||||
// 3. 用户自定义处理(钩子)
|
||||
onCreated?.Invoke(system);
|
||||
|
||||
_logger.Debug($"System created: {typeof(T).Name}");
|
||||
return system;
|
||||
});
|
||||
|
||||
_logger.Info($"System type registered: {typeof(T).Name}");
|
||||
_componentRegistry.RegisterSystem(onCreated);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个模型到架构中。
|
||||
/// 若当前未初始化,则暂存至待初始化列表;否则立即初始化该模型。
|
||||
/// 注册一个模型到架构中
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">要注册的模型类型,必须实现IModel接口</typeparam>
|
||||
/// <typeparam name="TModel">要注册的模型类型</typeparam>
|
||||
/// <param name="model">要注册的模型实例</param>
|
||||
/// <returns>注册成功的模型实例</returns>
|
||||
public TModel RegisterModel<TModel>(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}");
|
||||
return model;
|
||||
return _componentRegistry.RegisterModel(model);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册模型类型,由 DI 容器自动创建实例
|
||||
/// 注册模型类型,由 DI 容器自动创建实例
|
||||
/// </summary>
|
||||
/// <typeparam name="T">模型类型</typeparam>
|
||||
/// <param name="onCreated">可选的实例创建后回调,用于自定义配置</param>
|
||||
/// <param name="onCreated">可选的实例创建后回调</param>
|
||||
public void RegisterModel<T>(Action<T>? onCreated = null) where T : class, IModel
|
||||
{
|
||||
ValidateRegistration("model");
|
||||
_logger.Debug($"Registering model type: {typeof(T).Name}");
|
||||
|
||||
Container.RegisterFactory<T>(sp =>
|
||||
{
|
||||
var model = ActivatorUtilities.CreateInstance<T>(sp);
|
||||
model.SetContext(Context);
|
||||
RegisterLifecycleComponent(model);
|
||||
|
||||
// 用户自定义钩子
|
||||
onCreated?.Invoke(model);
|
||||
|
||||
_logger.Debug($"Model created: {typeof(T).Name}");
|
||||
return model;
|
||||
});
|
||||
|
||||
_logger.Info($"Model type registered: {typeof(T).Name}");
|
||||
_componentRegistry.RegisterModel(onCreated);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个工具到架构中
|
||||
/// </summary>
|
||||
/// <typeparam name="TUtility">要注册的工具类型,必须实现IUtility接口</typeparam>
|
||||
/// <typeparam name="TUtility">要注册的工具类型</typeparam>
|
||||
/// <param name="utility">要注册的工具实例</param>
|
||||
/// <returns>注册成功的工具实例</returns>
|
||||
public TUtility RegisterUtility<TUtility>(TUtility utility) where TUtility : IUtility
|
||||
{
|
||||
_logger.Debug($"Registering utility: {typeof(TUtility).Name}");
|
||||
|
||||
// 处理上下文工具类型的设置和生命周期管理
|
||||
utility.IfType<IContextUtility>(contextUtility =>
|
||||
{
|
||||
contextUtility.SetContext(Context);
|
||||
// 处理生命周期
|
||||
RegisterLifecycleComponent(contextUtility);
|
||||
});
|
||||
|
||||
Container.RegisterPlurality(utility);
|
||||
_logger.Info($"Utility registered: {typeof(TUtility).Name}");
|
||||
return utility;
|
||||
return _componentRegistry.RegisterUtility(utility);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册工具类型,由 DI 容器自动创建实例
|
||||
/// 注册工具类型,由 DI 容器自动创建实例
|
||||
/// </summary>
|
||||
/// <typeparam name="T">工具类型</typeparam>
|
||||
/// <param name="onCreated">可选的实例创建后回调,用于自定义配置</param>
|
||||
/// <param name="onCreated">可选的实例创建后回调</param>
|
||||
public void RegisterUtility<T>(Action<T>? onCreated = null) where T : class, IUtility
|
||||
{
|
||||
_logger.Debug($"Registering utility type: {typeof(T).Name}");
|
||||
|
||||
Container.RegisterFactory<T>(sp =>
|
||||
{
|
||||
var utility = ActivatorUtilities.CreateInstance<T>(sp);
|
||||
|
||||
// 如果是 IContextUtility,设置上下文
|
||||
if (utility is IContextUtility contextUtility)
|
||||
{
|
||||
contextUtility.SetContext(Context);
|
||||
RegisterLifecycleComponent(contextUtility);
|
||||
}
|
||||
|
||||
// 用户自定义钩子
|
||||
onCreated?.Invoke(utility);
|
||||
|
||||
_logger.Debug($"Utility created: {typeof(T).Name}");
|
||||
return utility;
|
||||
});
|
||||
|
||||
_logger.Info($"Utility type registered: {typeof(T).Name}");
|
||||
_componentRegistry.RegisterUtility(onCreated);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Initialization
|
||||
|
||||
/// <summary>
|
||||
/// 抽象初始化方法,由子类重写以进行自定义初始化操作
|
||||
/// </summary>
|
||||
protected abstract void OnInitialize();
|
||||
|
||||
/// <summary>
|
||||
/// 同步初始化方法,阻塞当前线程直到初始化完成
|
||||
/// </summary>
|
||||
@ -606,7 +256,7 @@ public abstract class Architecture(
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Architecture initialization failed:", e);
|
||||
EnterPhase(ArchitecturePhase.FailedInitialization);
|
||||
_lifecycle.MarkAsFailed(e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -614,7 +264,6 @@ public abstract class Architecture(
|
||||
/// <summary>
|
||||
/// 异步初始化方法,返回Task以便调用者可以等待初始化完成
|
||||
/// </summary>
|
||||
/// <returns>表示异步初始化操作的Task</returns>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
@ -624,32 +273,29 @@ public abstract class Architecture(
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Architecture initialization failed:", e);
|
||||
EnterPhase(ArchitecturePhase.FailedInitialization);
|
||||
_lifecycle.MarkAsFailed(e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步初始化架构内部组件,包括上下文、模型和系统的初始化
|
||||
/// 异步初始化架构内部组件
|
||||
/// </summary>
|
||||
/// <param name="asyncMode">是否启用异步模式进行组件初始化</param>
|
||||
/// <returns>异步任务,表示初始化操作的完成</returns>
|
||||
/// <param name="asyncMode">是否启用异步模式</param>
|
||||
private async Task InitializeInternalAsync(bool asyncMode)
|
||||
{
|
||||
// === 基础上下文 & Logger ===
|
||||
LoggerFactoryResolver.Provider = Configuration.LoggerProperties.LoggerFactoryProvider;
|
||||
_logger = LoggerFactoryResolver.Provider.CreateLogger(GetType().Name);
|
||||
// === 基础环境初始化 ===
|
||||
Environment.Initialize();
|
||||
|
||||
// 注册内置服务模块
|
||||
Services.ModuleManager.RegisterBuiltInModules(Container);
|
||||
Services.ModuleManager.RegisterBuiltInModules(Services.Container);
|
||||
|
||||
// 将 Environment 注册到容器(如果尚未注册)
|
||||
if (!Container.Contains<IEnvironment>())
|
||||
Container.RegisterPlurality(Environment);
|
||||
// 将 Environment 注册到容器
|
||||
if (!Services.Container.Contains<IEnvironment>())
|
||||
Services.Container.RegisterPlurality(Environment);
|
||||
|
||||
// 初始化架构上下文(如果尚未初始化)
|
||||
_context ??= new ArchitectureContext(Container);
|
||||
// 初始化架构上下文
|
||||
_context ??= new ArchitectureContext(Services.Container);
|
||||
GameContext.Bind(GetType(), _context);
|
||||
|
||||
// 为服务设置上下文
|
||||
@ -660,7 +306,7 @@ public abstract class Architecture(
|
||||
}
|
||||
|
||||
// 执行服务钩子
|
||||
Container.ExecuteServicesHook(Configurator);
|
||||
Services.Container.ExecuteServicesHook(Configurator);
|
||||
|
||||
// 初始化服务模块
|
||||
await Services.ModuleManager.InitializeAllAsync(asyncMode);
|
||||
@ -671,39 +317,44 @@ public abstract class Architecture(
|
||||
_logger.Debug("User OnInitialize() completed");
|
||||
|
||||
// === 组件初始化阶段 ===
|
||||
await InitializeAllComponentsAsync(asyncMode);
|
||||
await _lifecycle.InitializeAllComponentsAsync(asyncMode);
|
||||
|
||||
// === 初始化完成阶段 ===
|
||||
Container.Freeze();
|
||||
Services.Container.Freeze();
|
||||
_logger.Info("IOC container frozen");
|
||||
|
||||
_mInitialized = true;
|
||||
EnterPhase(ArchitecturePhase.Ready);
|
||||
// 🔥 释放 Ready await
|
||||
_readyTcs.TrySetResult();
|
||||
|
||||
_lifecycle.MarkAsReady();
|
||||
_logger.Info($"Architecture {GetType().Name} is ready - all components initialized");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待架构初始化完成(Ready 阶段)
|
||||
/// 如果架构已经处于就绪状态,则立即返回已完成的任务;
|
||||
/// 否则返回一个任务,该任务将在架构进入就绪状态时完成。
|
||||
/// </summary>
|
||||
/// <returns>表示等待操作的Task对象</returns>
|
||||
public Task WaitUntilReadyAsync()
|
||||
{
|
||||
return IsReady ? Task.CompletedTask : _readyTcs.Task;
|
||||
return _lifecycle.WaitUntilReadyAsync();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Destruction
|
||||
|
||||
/// <summary>
|
||||
/// 异步销毁架构及所有组件
|
||||
/// </summary>
|
||||
public virtual async ValueTask DestroyAsync()
|
||||
{
|
||||
await _lifecycle.DestroyAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取用于配置服务集合的委托
|
||||
/// 默认实现返回null,子类可以重写此属性以提供自定义配置逻辑
|
||||
/// 销毁架构并清理所有组件资源(同步方法,保留用于向后兼容)
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// 一个可为空的Action委托,用于配置IServiceCollection实例
|
||||
/// </value>
|
||||
public virtual Action<IServiceCollection>? Configurator => null;
|
||||
[Obsolete("建议使用 DestroyAsync() 以支持异步清理")]
|
||||
public virtual void Destroy()
|
||||
{
|
||||
_lifecycle.Destroy();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
204
GFramework.Core/Architectures/ArchitectureComponentRegistry.cs
Normal file
204
GFramework.Core/Architectures/ArchitectureComponentRegistry.cs
Normal file
@ -0,0 +1,204 @@
|
||||
using GFramework.Core.Abstractions.Architectures;
|
||||
using GFramework.Core.Abstractions.Enums;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Abstractions.Model;
|
||||
using GFramework.Core.Abstractions.Systems;
|
||||
using GFramework.Core.Abstractions.Utility;
|
||||
using GFramework.Core.Extensions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace GFramework.Core.Architectures;
|
||||
|
||||
/// <summary>
|
||||
/// 架构组件注册管理器
|
||||
/// 负责管理 System、Model、Utility 的注册
|
||||
/// </summary>
|
||||
internal sealed class ArchitectureComponentRegistry(
|
||||
IArchitecture architecture,
|
||||
IArchitectureConfiguration configuration,
|
||||
IArchitectureServices services,
|
||||
ArchitectureLifecycle lifecycle,
|
||||
ILogger logger)
|
||||
{
|
||||
#region Validation
|
||||
|
||||
/// <summary>
|
||||
/// 验证是否允许注册组件
|
||||
/// </summary>
|
||||
/// <param name="componentType">组件类型描述</param>
|
||||
/// <exception cref="InvalidOperationException">当不允许注册时抛出</exception>
|
||||
private void ValidateRegistration(string componentType)
|
||||
{
|
||||
if (lifecycle.CurrentPhase < ArchitecturePhase.Ready ||
|
||||
configuration.ArchitectureProperties.AllowLateRegistration) return;
|
||||
var errorMsg = $"Cannot register {componentType} after Architecture is Ready";
|
||||
logger.Error(errorMsg);
|
||||
throw new InvalidOperationException(errorMsg);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region System Registration
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个系统到架构中
|
||||
/// </summary>
|
||||
/// <typeparam name="TSystem">要注册的系统类型</typeparam>
|
||||
/// <param name="system">要注册的系统实例</param>
|
||||
/// <returns>注册成功的系统实例</returns>
|
||||
public TSystem RegisterSystem<TSystem>(TSystem system) where TSystem : ISystem
|
||||
{
|
||||
ValidateRegistration("system");
|
||||
|
||||
logger.Debug($"Registering system: {typeof(TSystem).Name}");
|
||||
|
||||
system.SetContext(architecture.Context);
|
||||
services.Container.RegisterPlurality(system);
|
||||
|
||||
// 处理生命周期
|
||||
lifecycle.RegisterLifecycleComponent(system);
|
||||
|
||||
logger.Info($"System registered: {typeof(TSystem).Name}");
|
||||
return system;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册系统类型,由 DI 容器自动创建实例
|
||||
/// </summary>
|
||||
/// <typeparam name="T">系统类型</typeparam>
|
||||
/// <param name="onCreated">可选的实例创建后回调</param>
|
||||
public void RegisterSystem<T>(Action<T>? onCreated = null) where T : class, ISystem
|
||||
{
|
||||
ValidateRegistration("system");
|
||||
logger.Debug($"Registering system type: {typeof(T).Name}");
|
||||
|
||||
services.Container.RegisterFactory<T>(sp =>
|
||||
{
|
||||
// 1. DI 创建实例
|
||||
var system = ActivatorUtilities.CreateInstance<T>(sp);
|
||||
|
||||
// 2. 框架默认处理
|
||||
system.SetContext(architecture.Context);
|
||||
lifecycle.RegisterLifecycleComponent(system);
|
||||
|
||||
// 3. 用户自定义处理(钩子)
|
||||
onCreated?.Invoke(system);
|
||||
|
||||
logger.Debug($"System created: {typeof(T).Name}");
|
||||
return system;
|
||||
});
|
||||
|
||||
logger.Info($"System type registered: {typeof(T).Name}");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Model Registration
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个模型到架构中
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">要注册的模型类型</typeparam>
|
||||
/// <param name="model">要注册的模型实例</param>
|
||||
/// <returns>注册成功的模型实例</returns>
|
||||
public TModel RegisterModel<TModel>(TModel model) where TModel : IModel
|
||||
{
|
||||
ValidateRegistration("model");
|
||||
|
||||
logger.Debug($"Registering model: {typeof(TModel).Name}");
|
||||
|
||||
model.SetContext(architecture.Context);
|
||||
services.Container.RegisterPlurality(model);
|
||||
|
||||
// 处理生命周期
|
||||
lifecycle.RegisterLifecycleComponent(model);
|
||||
|
||||
logger.Info($"Model registered: {typeof(TModel).Name}");
|
||||
return model;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册模型类型,由 DI 容器自动创建实例
|
||||
/// </summary>
|
||||
/// <typeparam name="T">模型类型</typeparam>
|
||||
/// <param name="onCreated">可选的实例创建后回调</param>
|
||||
public void RegisterModel<T>(Action<T>? onCreated = null) where T : class, IModel
|
||||
{
|
||||
ValidateRegistration("model");
|
||||
logger.Debug($"Registering model type: {typeof(T).Name}");
|
||||
|
||||
services.Container.RegisterFactory<T>(sp =>
|
||||
{
|
||||
var model = ActivatorUtilities.CreateInstance<T>(sp);
|
||||
model.SetContext(architecture.Context);
|
||||
lifecycle.RegisterLifecycleComponent(model);
|
||||
|
||||
// 用户自定义钩子
|
||||
onCreated?.Invoke(model);
|
||||
|
||||
logger.Debug($"Model created: {typeof(T).Name}");
|
||||
return model;
|
||||
});
|
||||
|
||||
logger.Info($"Model type registered: {typeof(T).Name}");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Utility Registration
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个工具到架构中
|
||||
/// </summary>
|
||||
/// <typeparam name="TUtility">要注册的工具类型</typeparam>
|
||||
/// <param name="utility">要注册的工具实例</param>
|
||||
/// <returns>注册成功的工具实例</returns>
|
||||
public TUtility RegisterUtility<TUtility>(TUtility utility) where TUtility : IUtility
|
||||
{
|
||||
logger.Debug($"Registering utility: {typeof(TUtility).Name}");
|
||||
|
||||
// 处理上下文工具类型的设置和生命周期管理
|
||||
utility.IfType<IContextUtility>(contextUtility =>
|
||||
{
|
||||
contextUtility.SetContext(architecture.Context);
|
||||
// 处理生命周期
|
||||
lifecycle.RegisterLifecycleComponent(contextUtility);
|
||||
});
|
||||
|
||||
services.Container.RegisterPlurality(utility);
|
||||
logger.Info($"Utility registered: {typeof(TUtility).Name}");
|
||||
return utility;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册工具类型,由 DI 容器自动创建实例
|
||||
/// </summary>
|
||||
/// <typeparam name="T">工具类型</typeparam>
|
||||
/// <param name="onCreated">可选的实例创建后回调</param>
|
||||
public void RegisterUtility<T>(Action<T>? onCreated = null) where T : class, IUtility
|
||||
{
|
||||
logger.Debug($"Registering utility type: {typeof(T).Name}");
|
||||
|
||||
services.Container.RegisterFactory<T>(sp =>
|
||||
{
|
||||
var utility = ActivatorUtilities.CreateInstance<T>(sp);
|
||||
|
||||
// 如果是 IContextUtility,设置上下文
|
||||
if (utility is IContextUtility contextUtility)
|
||||
{
|
||||
contextUtility.SetContext(architecture.Context);
|
||||
lifecycle.RegisterLifecycleComponent(contextUtility);
|
||||
}
|
||||
|
||||
// 用户自定义钩子
|
||||
onCreated?.Invoke(utility);
|
||||
|
||||
logger.Debug($"Utility created: {typeof(T).Name}");
|
||||
return utility;
|
||||
});
|
||||
|
||||
logger.Info($"Utility type registered: {typeof(T).Name}");
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
420
GFramework.Core/Architectures/ArchitectureLifecycle.cs
Normal file
420
GFramework.Core/Architectures/ArchitectureLifecycle.cs
Normal file
@ -0,0 +1,420 @@
|
||||
using GFramework.Core.Abstractions.Architectures;
|
||||
using GFramework.Core.Abstractions.Enums;
|
||||
using GFramework.Core.Abstractions.Lifecycle;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
using GFramework.Core.Abstractions.Model;
|
||||
using GFramework.Core.Abstractions.Systems;
|
||||
using GFramework.Core.Abstractions.Utility;
|
||||
|
||||
namespace GFramework.Core.Architectures;
|
||||
|
||||
/// <summary>
|
||||
/// 架构生命周期管理器
|
||||
/// 负责管理架构的阶段转换、组件初始化和销毁
|
||||
/// </summary>
|
||||
internal sealed class ArchitectureLifecycle(
|
||||
IArchitecture architecture,
|
||||
IArchitectureConfiguration configuration,
|
||||
IArchitectureServices services,
|
||||
ILogger logger)
|
||||
{
|
||||
#region Lifecycle Hook Management
|
||||
|
||||
/// <summary>
|
||||
/// 注册生命周期钩子
|
||||
/// </summary>
|
||||
/// <param name="hook">生命周期钩子实例</param>
|
||||
/// <returns>注册的钩子实例</returns>
|
||||
public IArchitectureLifecycleHook RegisterLifecycleHook(IArchitectureLifecycleHook hook)
|
||||
{
|
||||
if (CurrentPhase >= ArchitecturePhase.Ready && !configuration.ArchitectureProperties.AllowLateRegistration)
|
||||
throw new InvalidOperationException(
|
||||
"Cannot register lifecycle hook after architecture is Ready");
|
||||
_lifecycleHooks.Add(hook);
|
||||
return hook;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Component Lifecycle Management
|
||||
|
||||
/// <summary>
|
||||
/// 统一的组件生命周期注册逻辑
|
||||
/// </summary>
|
||||
/// <param name="component">要注册的组件</param>
|
||||
public void RegisterLifecycleComponent(object component)
|
||||
{
|
||||
// 处理初始化
|
||||
if (component is IInitializable initializable)
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
// 原子去重:HashSet.Add 返回 true 表示添加成功(之前不存在)
|
||||
if (_pendingInitializableSet.Add(initializable))
|
||||
{
|
||||
_pendingInitializableList.Add(initializable);
|
||||
logger.Trace($"Added {component.GetType().Name} to pending initialization queue");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Cannot initialize component after Architecture is Ready");
|
||||
}
|
||||
}
|
||||
|
||||
// 处理销毁(支持 IDestroyable 或 IAsyncDestroyable)
|
||||
if (component is not (IDestroyable or IAsyncDestroyable)) return;
|
||||
// 原子去重:HashSet.Add 返回 true 表示添加成功(之前不存在)
|
||||
if (!_disposableSet.Add(component)) return;
|
||||
_disposables.Add(component);
|
||||
logger.Trace($"Registered {component.GetType().Name} for destruction");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Fields
|
||||
|
||||
private readonly TaskCompletionSource _readyTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
/// <summary>
|
||||
/// 待初始化组件的去重集合
|
||||
/// </summary>
|
||||
private readonly HashSet<IInitializable> _pendingInitializableSet = [];
|
||||
|
||||
/// <summary>
|
||||
/// 存储所有待初始化的组件(统一管理,保持注册顺序)
|
||||
/// </summary>
|
||||
private readonly List<IInitializable> _pendingInitializableList = [];
|
||||
|
||||
/// <summary>
|
||||
/// 可销毁组件的去重集合(支持 IDestroyable 和 IAsyncDestroyable)
|
||||
/// </summary>
|
||||
private readonly HashSet<object> _disposableSet = [];
|
||||
|
||||
/// <summary>
|
||||
/// 存储所有需要销毁的组件(统一管理,保持注册逆序销毁)
|
||||
/// </summary>
|
||||
private readonly List<object> _disposables = [];
|
||||
|
||||
/// <summary>
|
||||
/// 生命周期感知对象列表
|
||||
/// </summary>
|
||||
private readonly List<IArchitectureLifecycleHook> _lifecycleHooks = [];
|
||||
|
||||
/// <summary>
|
||||
/// 标记架构是否已初始化完成
|
||||
/// </summary>
|
||||
private bool _initialized;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>
|
||||
/// 当前架构的阶段
|
||||
/// </summary>
|
||||
public ArchitecturePhase CurrentPhase { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个布尔值,指示当前架构是否处于就绪状态
|
||||
/// </summary>
|
||||
public bool IsReady => CurrentPhase == ArchitecturePhase.Ready;
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个布尔值,指示架构是否已初始化
|
||||
/// </summary>
|
||||
public bool IsInitialized => _initialized;
|
||||
|
||||
/// <summary>
|
||||
/// 阶段变更事件(用于测试和扩展)
|
||||
/// </summary>
|
||||
public event Action<ArchitecturePhase>? PhaseChanged;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Phase Management
|
||||
|
||||
/// <summary>
|
||||
/// 进入指定的架构阶段,并执行相应的生命周期管理操作
|
||||
/// </summary>
|
||||
/// <param name="next">要进入的下一个架构阶段</param>
|
||||
/// <exception cref="InvalidOperationException">当阶段转换不被允许时抛出异常</exception>
|
||||
public void EnterPhase(ArchitecturePhase next)
|
||||
{
|
||||
// 验证阶段转换
|
||||
ValidatePhaseTransition(next);
|
||||
|
||||
// 执行阶段转换
|
||||
var previousPhase = CurrentPhase;
|
||||
CurrentPhase = next;
|
||||
|
||||
if (previousPhase != next)
|
||||
logger.Info($"Architecture phase changed: {previousPhase} -> {next}");
|
||||
|
||||
// 通知阶段变更
|
||||
NotifyPhase(next);
|
||||
NotifyPhaseAwareObjects(next);
|
||||
|
||||
// 触发阶段变更事件(用于测试和扩展)
|
||||
PhaseChanged?.Invoke(next);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证阶段转换是否合法
|
||||
/// </summary>
|
||||
/// <param name="next">目标阶段</param>
|
||||
/// <exception cref="InvalidOperationException">当阶段转换不合法时抛出</exception>
|
||||
private void ValidatePhaseTransition(ArchitecturePhase next)
|
||||
{
|
||||
// 不需要严格验证,直接返回
|
||||
if (!configuration.ArchitectureProperties.StrictPhaseValidation)
|
||||
return;
|
||||
|
||||
// FailedInitialization 可以从任何阶段转换,直接返回
|
||||
if (next == ArchitecturePhase.FailedInitialization)
|
||||
return;
|
||||
|
||||
// 检查转换是否在允许列表中
|
||||
if (ArchitectureConstants.PhaseTransitions.TryGetValue(CurrentPhase, out var allowed) &&
|
||||
allowed.Contains(next))
|
||||
return;
|
||||
|
||||
// 转换不合法,抛出异常
|
||||
var errorMsg = $"Invalid phase transition: {CurrentPhase} -> {next}";
|
||||
logger.Fatal(errorMsg);
|
||||
throw new InvalidOperationException(errorMsg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通知所有架构阶段感知对象阶段变更
|
||||
/// </summary>
|
||||
/// <param name="phase">新阶段</param>
|
||||
private void NotifyPhaseAwareObjects(ArchitecturePhase phase)
|
||||
{
|
||||
foreach (var obj in services.Container.GetAll<IArchitecturePhaseListener>())
|
||||
{
|
||||
logger.Trace($"Notifying phase-aware object {obj.GetType().Name} of phase change to {phase}");
|
||||
obj.OnArchitecturePhase(phase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通知所有生命周期钩子当前阶段变更
|
||||
/// </summary>
|
||||
/// <param name="phase">当前架构阶段</param>
|
||||
private void NotifyPhase(ArchitecturePhase phase)
|
||||
{
|
||||
foreach (var hook in _lifecycleHooks)
|
||||
{
|
||||
hook.OnPhase(phase, architecture);
|
||||
logger.Trace($"Notifying lifecycle hook {hook.GetType().Name} of phase {phase}");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Initialization
|
||||
|
||||
/// <summary>
|
||||
/// 初始化所有待初始化的组件
|
||||
/// </summary>
|
||||
/// <param name="asyncMode">是否使用异步模式</param>
|
||||
public async Task InitializeAllComponentsAsync(bool asyncMode)
|
||||
{
|
||||
logger.Info($"Initializing {_pendingInitializableList.Count} components");
|
||||
|
||||
// 按类型分组初始化(保持原有的阶段划分)
|
||||
var utilities = _pendingInitializableList.OfType<IContextUtility>().ToList();
|
||||
var models = _pendingInitializableList.OfType<IModel>().ToList();
|
||||
var systems = _pendingInitializableList.OfType<ISystem>().ToList();
|
||||
|
||||
// 1. 工具初始化阶段
|
||||
EnterPhase(ArchitecturePhase.BeforeUtilityInit);
|
||||
|
||||
if (utilities.Count != 0)
|
||||
{
|
||||
logger.Info($"Initializing {utilities.Count} context utilities");
|
||||
|
||||
foreach (var utility in utilities)
|
||||
{
|
||||
logger.Debug($"Initializing utility: {utility.GetType().Name}");
|
||||
await InitializeComponentAsync(utility, asyncMode);
|
||||
}
|
||||
|
||||
logger.Info("All context utilities initialized");
|
||||
}
|
||||
|
||||
EnterPhase(ArchitecturePhase.AfterUtilityInit);
|
||||
|
||||
// 2. 模型初始化阶段
|
||||
EnterPhase(ArchitecturePhase.BeforeModelInit);
|
||||
|
||||
if (models.Count != 0)
|
||||
{
|
||||
logger.Info($"Initializing {models.Count} models");
|
||||
|
||||
foreach (var model in models)
|
||||
{
|
||||
logger.Debug($"Initializing model: {model.GetType().Name}");
|
||||
await InitializeComponentAsync(model, asyncMode);
|
||||
}
|
||||
|
||||
logger.Info("All models initialized");
|
||||
}
|
||||
|
||||
EnterPhase(ArchitecturePhase.AfterModelInit);
|
||||
|
||||
// 3. 系统初始化阶段
|
||||
EnterPhase(ArchitecturePhase.BeforeSystemInit);
|
||||
|
||||
if (systems.Count != 0)
|
||||
{
|
||||
logger.Info($"Initializing {systems.Count} systems");
|
||||
|
||||
foreach (var system in systems)
|
||||
{
|
||||
logger.Debug($"Initializing system: {system.GetType().Name}");
|
||||
await InitializeComponentAsync(system, asyncMode);
|
||||
}
|
||||
|
||||
logger.Info("All systems initialized");
|
||||
}
|
||||
|
||||
EnterPhase(ArchitecturePhase.AfterSystemInit);
|
||||
|
||||
_pendingInitializableList.Clear();
|
||||
_pendingInitializableSet.Clear();
|
||||
_initialized = true;
|
||||
logger.Info("All components initialized");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步初始化单个组件
|
||||
/// </summary>
|
||||
/// <param name="component">要初始化的组件</param>
|
||||
/// <param name="asyncMode">是否使用异步模式</param>
|
||||
private static async Task InitializeComponentAsync(IInitializable component, bool asyncMode)
|
||||
{
|
||||
if (asyncMode && component is IAsyncInitializable asyncInit)
|
||||
await asyncInit.InitializeAsync();
|
||||
else
|
||||
component.Initialize();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Destruction
|
||||
|
||||
/// <summary>
|
||||
/// 异步销毁架构及所有组件
|
||||
/// </summary>
|
||||
public async ValueTask DestroyAsync()
|
||||
{
|
||||
// 检查当前阶段,如果已经处于销毁或已销毁状态则直接返回
|
||||
if (CurrentPhase >= ArchitecturePhase.Destroying)
|
||||
{
|
||||
logger.Warn("Architecture destroy called but already in destroying/destroyed state");
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果从未初始化(None 阶段),只清理已注册的组件,不进行阶段转换
|
||||
if (CurrentPhase == ArchitecturePhase.None)
|
||||
{
|
||||
logger.Debug("Architecture destroy called but never initialized, cleaning up registered components");
|
||||
await CleanupComponentsAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
// 进入销毁阶段
|
||||
logger.Info("Starting architecture destruction");
|
||||
EnterPhase(ArchitecturePhase.Destroying);
|
||||
|
||||
// 清理所有组件
|
||||
await CleanupComponentsAsync();
|
||||
|
||||
// 销毁服务模块
|
||||
await services.ModuleManager.DestroyAllAsync();
|
||||
|
||||
services.Container.Clear();
|
||||
|
||||
// 进入已销毁阶段
|
||||
EnterPhase(ArchitecturePhase.Destroyed);
|
||||
logger.Info("Architecture destruction completed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理所有已注册的可销毁组件
|
||||
/// </summary>
|
||||
private async ValueTask CleanupComponentsAsync()
|
||||
{
|
||||
// 销毁所有实现了 IAsyncDestroyable 或 IDestroyable 的组件(按注册逆序销毁)
|
||||
logger.Info($"Destroying {_disposables.Count} disposable components");
|
||||
|
||||
for (var i = _disposables.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var component = _disposables[i];
|
||||
try
|
||||
{
|
||||
logger.Debug($"Destroying component: {component.GetType().Name}");
|
||||
|
||||
// 优先使用异步销毁
|
||||
if (component is IAsyncDestroyable asyncDestroyable)
|
||||
{
|
||||
await asyncDestroyable.DestroyAsync();
|
||||
}
|
||||
else if (component is IDestroyable destroyable)
|
||||
{
|
||||
destroyable.Destroy();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.Error($"Error destroying {component.GetType().Name}", ex);
|
||||
// 继续销毁其他组件,不会因为一个组件失败而中断
|
||||
}
|
||||
}
|
||||
|
||||
_disposables.Clear();
|
||||
_disposableSet.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁架构并清理所有组件资源(同步方法,保留用于向后兼容)
|
||||
/// </summary>
|
||||
[Obsolete("建议使用 DestroyAsync() 以支持异步清理")]
|
||||
public void Destroy()
|
||||
{
|
||||
DestroyAsync().AsTask().GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Ready State
|
||||
|
||||
/// <summary>
|
||||
/// 标记架构为就绪状态
|
||||
/// </summary>
|
||||
public void MarkAsReady()
|
||||
{
|
||||
EnterPhase(ArchitecturePhase.Ready);
|
||||
_readyTcs.TrySetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标记架构初始化失败
|
||||
/// </summary>
|
||||
/// <param name="exception">失败异常</param>
|
||||
public void MarkAsFailed(Exception exception)
|
||||
{
|
||||
EnterPhase(ArchitecturePhase.FailedInitialization);
|
||||
_readyTcs.TrySetException(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待架构就绪
|
||||
/// </summary>
|
||||
public Task WaitUntilReadyAsync() => _readyTcs.Task;
|
||||
|
||||
#endregion
|
||||
}
|
||||
39
GFramework.Core/Architectures/ArchitectureModules.cs
Normal file
39
GFramework.Core/Architectures/ArchitectureModules.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using GFramework.Core.Abstractions.Architectures;
|
||||
using GFramework.Core.Abstractions.Logging;
|
||||
|
||||
namespace GFramework.Core.Architectures;
|
||||
|
||||
/// <summary>
|
||||
/// 架构模块管理器
|
||||
/// 负责管理架构模块的安装和中介行为注册
|
||||
/// </summary>
|
||||
internal sealed class ArchitectureModules(
|
||||
IArchitecture architecture,
|
||||
IArchitectureServices services,
|
||||
ILogger logger)
|
||||
{
|
||||
/// <summary>
|
||||
/// 注册中介行为管道
|
||||
/// 用于配置Mediator框架的行为拦截和处理逻辑
|
||||
/// </summary>
|
||||
/// <typeparam name="TBehavior">行为类型,必须是引用类型</typeparam>
|
||||
public void RegisterMediatorBehavior<TBehavior>() where TBehavior : class
|
||||
{
|
||||
logger.Debug($"Registering mediator behavior: {typeof(TBehavior).Name}");
|
||||
services.Container.RegisterMediatorBehavior<TBehavior>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 安装架构模块
|
||||
/// </summary>
|
||||
/// <param name="module">要安装的模块</param>
|
||||
/// <returns>安装的模块实例</returns>
|
||||
public IArchitectureModule InstallModule(IArchitectureModule module)
|
||||
{
|
||||
var name = module.GetType().Name;
|
||||
logger.Debug($"Installing module: {name}");
|
||||
module.Install(architecture);
|
||||
logger.Info($"Module installed: {name}");
|
||||
return module;
|
||||
}
|
||||
}
|
||||
@ -122,4 +122,7 @@
|
||||
<AdditionalFiles Remove="AnalyzerReleases.Shipped.md"/>
|
||||
<AdditionalFiles Remove="AnalyzerReleases.Unshipped.md"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="local-plan\评估\"/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -129,7 +129,7 @@ public interface IQuery<TResult>
|
||||
|
||||
### IIocContainer
|
||||
|
||||
IOC 容器接口:
|
||||
IoC 容器接口:
|
||||
|
||||
```csharp
|
||||
public interface IIocContainer
|
||||
|
||||
@ -1,608 +1,231 @@
|
||||
# Architecture 包使用说明
|
||||
# Architecture 架构详解
|
||||
|
||||
> 深入了解 GFramework 的核心架构设计和实现
|
||||
|
||||
## 目录
|
||||
|
||||
- [概述](#概述)
|
||||
- [架构设计](#架构设计)
|
||||
- [生命周期管理](#生命周期管理)
|
||||
- [组件注册](#组件注册)
|
||||
- [模块系统](#模块系统)
|
||||
- [最佳实践](#最佳实践)
|
||||
- [API 参考](#api-参考)
|
||||
|
||||
## 概述
|
||||
|
||||
Architecture 包是整个框架的核心,提供了基于分层架构模式的应用程序架构基础。它实现了依赖注入(IoC)
|
||||
容器、组件生命周期管理,以及命令、查询、事件的统一调度机制。
|
||||
Architecture 是 GFramework 的核心类,负责管理整个应用的生命周期、组件注册和模块管理。从 v1.1.0 开始,Architecture
|
||||
采用模块化设计,将职责分离到专门的管理器中。
|
||||
|
||||
**注意**:本框架的 Core 模块与 Godot 解耦,Godot 相关集成在 GFramework.Godot 包中实现。
|
||||
### 设计目标
|
||||
|
||||
## 核心接口
|
||||
- **单一职责**: 每个管理器只负责一个明确的功能
|
||||
- **类型安全**: 基于泛型的组件获取和注册
|
||||
- **生命周期管理**: 自动的初始化和销毁机制
|
||||
- **可扩展性**: 支持模块和钩子扩展
|
||||
- **向后兼容**: 保持公共 API 稳定
|
||||
|
||||
### IArchitecture
|
||||
### 核心组件
|
||||
|
||||
架构接口,定义了框架的核心功能契约。
|
||||
|
||||
**主要职责:**
|
||||
|
||||
- **组件注册**:注册 System、Model、Utility
|
||||
- **组件获取**:从容器中获取已注册的组件
|
||||
- **命令处理**:发送并执行命令
|
||||
- **查询处理**:发送并执行查询
|
||||
- **事件管理**:发送、注册、注销事件
|
||||
- **模块管理**:安装和管理架构模块
|
||||
- **生命周期管理**:管理架构的初始化、运行和销毁阶段
|
||||
|
||||
**核心方法:**
|
||||
```csharp
|
||||
// 组件注册
|
||||
void RegisterSystem<TSystem>(TSystem system) where TSystem : ISystem;
|
||||
void RegisterModel<TModel>(TModel model) where TModel : IModel;
|
||||
void RegisterUtility<TUtility>(TUtility utility) where TUtility : IUtility;
|
||||
|
||||
// 组件获取(通过容器)
|
||||
T GetModel<T>() where T : class, IModel;
|
||||
T GetSystem<T>() where T : class, ISystem;
|
||||
T GetUtility<T>() where T : class, IUtility;
|
||||
|
||||
// 命令处理
|
||||
void SendCommand(ICommand command);
|
||||
TResult SendCommand<TResult>(ICommand<TResult> command);
|
||||
|
||||
// 查询处理
|
||||
TResult SendQuery<TResult>(IQuery<TResult> query);
|
||||
|
||||
// 事件管理
|
||||
void SendEvent<T>() where T : new();
|
||||
void SendEvent<T>(T e);
|
||||
IUnRegister RegisterEvent<T>(Action<T> onEvent);
|
||||
void UnRegisterEvent<T>(Action<T> onEvent);
|
||||
```
|
||||
Architecture (核心协调器)
|
||||
├── ArchitectureLifecycle (生命周期管理)
|
||||
├── ArchitectureComponentRegistry (组件注册)
|
||||
└── ArchitectureModules (模块管理)
|
||||
```
|
||||
|
||||
### IArchitecturePhaseAware
|
||||
## 架构设计
|
||||
|
||||
架构阶段感知接口,允许组件监听架构阶段变化。
|
||||
### 设计模式
|
||||
|
||||
**核心方法:**
|
||||
```csharp
|
||||
void OnArchitecturePhase(ArchitecturePhase phase);
|
||||
Architecture 采用以下设计模式:
|
||||
|
||||
1. **组合模式 (Composition)**: Architecture 组合三个管理器
|
||||
2. **委托模式 (Delegation)**: 方法调用委托给专门的管理器
|
||||
3. **协调器模式 (Coordinator)**: Architecture 作为协调器统一对外接口
|
||||
|
||||
### 类图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Architecture │
|
||||
│ - _lifecycle: ArchitectureLifecycle │
|
||||
│ - _componentRegistry: ArchitectureComponentRegistry│
|
||||
│ - _modules: ArchitectureModules │
|
||||
│ - _logger: ILogger │
|
||||
│ │
|
||||
│ + RegisterSystem<T>() │
|
||||
│ + RegisterModel<T>() │
|
||||
│ + RegisterUtility<T>() │
|
||||
│ + InstallModule() │
|
||||
│ + InitializeAsync() │
|
||||
│ + DestroyAsync() │
|
||||
│ + event PhaseChanged │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
│ │ │
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────────┐ ┌──────────────────┐ ┌──────────────┐
|
||||
│ Lifecycle │ │ ComponentRegistry│ │ Modules │
|
||||
│ │ │ │ │ │
|
||||
│ - 阶段管理 │ │ - System 注册 │ │ - 模块安装 │
|
||||
│ - 钩子管理 │ │ - Model 注册 │ │ - 行为注册 │
|
||||
│ - 初始化 │ │ - Utility 注册 │ │ │
|
||||
│ - 销毁 │ │ - 生命周期注册 │ │ │
|
||||
└──────────────┘ └──────────────────┘ └──────────────┘
|
||||
```
|
||||
|
||||
### IArchitectureModule
|
||||
### 构造函数初始化
|
||||
|
||||
架构模块接口,支持模块化架构扩展。
|
||||
从 v1.1.0 开始,所有管理器在构造函数中初始化:
|
||||
|
||||
**核心方法:**
|
||||
```csharp
|
||||
void Install(IArchitecture architecture);
|
||||
```
|
||||
|
||||
### IAsyncInitializable
|
||||
|
||||
异步初始化接口,支持组件异步初始化。
|
||||
|
||||
**核心方法:**
|
||||
```csharp
|
||||
Task InitializeAsync();
|
||||
```
|
||||
|
||||
## 核心类
|
||||
|
||||
### Architecture 架构基类
|
||||
|
||||
架构基类,实现了 `IArchitecture` 接口,提供完整的架构功能实现。
|
||||
|
||||
**构造函数参数:**
|
||||
```csharp
|
||||
public abstract class Architecture(
|
||||
protected Architecture(
|
||||
IArchitectureConfiguration? configuration = null,
|
||||
IEnvironment? environment = null,
|
||||
IArchitectureServices? services = null,
|
||||
IArchitectureContext? context = null
|
||||
)
|
||||
```
|
||||
|
||||
**特性:**
|
||||
|
||||
- **阶段式生命周期管理**
|
||||
:支持多个架构阶段(BeforeUtilityInit、AfterUtilityInit、BeforeModelInit、AfterModelInit、BeforeSystemInit、AfterSystemInit、Ready、FailedInitialization、Destroying、Destroyed)
|
||||
- **模块安装系统**:支持通过 `InstallModule` 扩展架构功能
|
||||
- **异步初始化**:支持同步和异步两种初始化方式
|
||||
- **IoC 容器集成**:内置依赖注入容器
|
||||
- **事件系统集成**:集成类型化事件系统
|
||||
- **与平台无关**:Core 模块不依赖 Godot,可以在任何 .NET 环境中使用
|
||||
- **严格的阶段验证**:可配置的阶段转换验证机制
|
||||
- **组件生命周期管理**:自动管理组件的初始化和销毁
|
||||
|
||||
**架构阶段:**
|
||||
```csharp
|
||||
public enum ArchitecturePhase
|
||||
IArchitectureContext? context = null)
|
||||
{
|
||||
None = 0, // 初始阶段
|
||||
BeforeUtilityInit = 1, // 工具初始化前
|
||||
AfterUtilityInit = 2, // 工具初始化后
|
||||
BeforeModelInit = 3, // 模型初始化前
|
||||
AfterModelInit = 4, // 模型初始化后
|
||||
BeforeSystemInit = 5, // 系统初始化前
|
||||
AfterSystemInit = 6, // 系统初始化后
|
||||
Ready = 7, // 就绪状态
|
||||
FailedInitialization = 8, // 初始化失败
|
||||
Destroying = 9, // 正在销毁
|
||||
Destroyed = 10 // 已销毁
|
||||
Configuration = configuration ?? new ArchitectureConfiguration();
|
||||
Environment = environment ?? new DefaultEnvironment();
|
||||
Services = services ?? new ArchitectureServices();
|
||||
_context = context;
|
||||
|
||||
// 初始化 Logger
|
||||
LoggerFactoryResolver.Provider = Configuration.LoggerProperties.LoggerFactoryProvider;
|
||||
_logger = LoggerFactoryResolver.Provider.CreateLogger(GetType().Name);
|
||||
|
||||
// 初始化管理器
|
||||
_lifecycle = new ArchitectureLifecycle(this, Configuration, Services, _logger);
|
||||
_componentRegistry = new ArchitectureComponentRegistry(this, Configuration, Services, _lifecycle, _logger);
|
||||
_modules = new ArchitectureModules(this, Services, _logger);
|
||||
}
|
||||
```
|
||||
|
||||
**初始化流程:**
|
||||
**优势**:
|
||||
|
||||
1. 创建架构实例(传入配置或使用默认配置)
|
||||
2. 初始化基础上下文和日志系统
|
||||
3. 调用用户自定义的 `Init()` 方法
|
||||
4. 按顺序初始化组件:
|
||||
- 工具初始化(BeforeUtilityInit → AfterUtilityInit)
|
||||
- 模型初始化(BeforeModelInit → AfterModelInit)
|
||||
- 系统初始化(BeforeSystemInit → AfterSystemInit)
|
||||
5. 冻结 IOC 容器
|
||||
6. 进入 Ready 阶段
|
||||
- 消除 `null!` 断言,提高代码安全性
|
||||
- 对象在构造后立即可用
|
||||
- 符合"构造即完整"原则
|
||||
- 可以在 InitializeAsync 之前访问事件
|
||||
|
||||
**销毁流程:**
|
||||
## 生命周期管理
|
||||
|
||||
1. 进入 Destroying 阶段
|
||||
2. 按注册逆序销毁所有实现了 `IDisposable` 的组件
|
||||
3. 进入 Destroyed 阶段
|
||||
4. 清理所有资源
|
||||
### 架构阶段
|
||||
|
||||
**使用示例:**
|
||||
Architecture 定义了 11 个生命周期阶段:
|
||||
|
||||
| 阶段 | 说明 | 触发时机 |
|
||||
|------------------------|--------------|------------------|
|
||||
| `None` | 初始状态 | 构造函数完成后 |
|
||||
| `BeforeUtilityInit` | Utility 初始化前 | 开始初始化 Utility |
|
||||
| `AfterUtilityInit` | Utility 初始化后 | 所有 Utility 初始化完成 |
|
||||
| `BeforeModelInit` | Model 初始化前 | 开始初始化 Model |
|
||||
| `AfterModelInit` | Model 初始化后 | 所有 Model 初始化完成 |
|
||||
| `BeforeSystemInit` | System 初始化前 | 开始初始化 System |
|
||||
| `AfterSystemInit` | System 初始化后 | 所有 System 初始化完成 |
|
||||
| `Ready` | 就绪状态 | 所有组件初始化完成 |
|
||||
| `Destroying` | 销毁中 | 开始销毁 |
|
||||
| `Destroyed` | 已销毁 | 销毁完成 |
|
||||
| `FailedInitialization` | 初始化失败 | 初始化过程中发生异常 |
|
||||
|
||||
### 阶段转换
|
||||
|
||||
```
|
||||
正常流程:
|
||||
None → BeforeUtilityInit → AfterUtilityInit → BeforeModelInit → AfterModelInit
|
||||
→ BeforeSystemInit → AfterSystemInit → Ready → Destroying → Destroyed
|
||||
|
||||
异常流程:
|
||||
Any → FailedInitialization
|
||||
```
|
||||
|
||||
### 阶段事件
|
||||
|
||||
可以通过 `PhaseChanged` 事件监听阶段变化:
|
||||
|
||||
```csharp
|
||||
// 1. 定义你的架构(继承 Architecture 基类)
|
||||
public class GameArchitecture : Architecture
|
||||
public class MyArchitecture : Architecture
|
||||
{
|
||||
protected override void Init()
|
||||
protected override void OnInitialize()
|
||||
{
|
||||
// 注册 Model
|
||||
RegisterModel(new PlayerModel());
|
||||
RegisterModel(new InventoryModel());
|
||||
|
||||
// 注册 System
|
||||
RegisterSystem(new GameplaySystem());
|
||||
RegisterSystem(new SaveSystem());
|
||||
|
||||
// 注册 Utility
|
||||
RegisterUtility(new StorageUtility());
|
||||
RegisterUtility(new TimeUtility());
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 创建并初始化架构
|
||||
var architecture = new GameArchitecture();
|
||||
architecture.Initialize();
|
||||
|
||||
// 或者异步初始化
|
||||
// var architecture = new GameArchitecture();
|
||||
// await architecture.InitializeAsync();
|
||||
|
||||
// 3. 等待架构就绪
|
||||
await architecture.WaitUntilReadyAsync();
|
||||
|
||||
// 4. 通过依赖注入使用架构
|
||||
// 在 Controller 或其他组件中获取架构实例
|
||||
using GFramework.Core.Abstractions.Controller;
|
||||
using GFramework.SourceGenerators.Abstractions.Rule;
|
||||
|
||||
[ContextAware]
|
||||
public partial class GameController : IController
|
||||
{
|
||||
public void Start()
|
||||
{
|
||||
// 获取 Model(使用扩展方法访问架构([ContextAware] 实现 IContextAware 接口))
|
||||
var playerModel = this.GetModel<PlayerModel>();
|
||||
|
||||
// 发送命令
|
||||
this.SendCommand(new StartGameCommand());
|
||||
|
||||
// 发送查询
|
||||
var score = this.SendQuery(new GetScoreQuery());
|
||||
|
||||
// 注册事件
|
||||
this.RegisterEvent<PlayerDiedEvent>(OnPlayerDied);
|
||||
}
|
||||
|
||||
private void OnPlayerDied(PlayerDiedEvent e)
|
||||
{
|
||||
// 处理玩家死亡事件
|
||||
// 监听阶段变化
|
||||
PhaseChanged += phase =>
|
||||
{
|
||||
Console.WriteLine($"Phase changed to: {phase}");
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**核心方法与属性:**
|
||||
### 生命周期钩子
|
||||
|
||||
#### 初始化方法
|
||||
|
||||
**Initialize()**
|
||||
|
||||
同步初始化方法,阻塞当前线程直到初始化完成。
|
||||
```csharp
|
||||
public void Initialize()
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 阻塞式初始化
|
||||
- 适用于简单场景或控制台应用
|
||||
- 初始化失败时抛出异常并进入 `FailedInitialization` 阶段
|
||||
|
||||
使用示例:
|
||||
```csharp
|
||||
var architecture = new GameArchitecture();
|
||||
architecture.Initialize(); // 阻塞等待初始化完成
|
||||
```
|
||||
|
||||
异常处理:如果初始化过程中发生异常,架构会进入 `FailedInitialization` 阶段。
|
||||
|
||||
**InitializeAsync()**
|
||||
|
||||
异步初始化方法,返回 Task 以便调用者可以等待初始化完成。
|
||||
```csharp
|
||||
public async Task InitializeAsync()
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 非阻塞式初始化
|
||||
- 支持异步组件初始化
|
||||
- 适用于需要异步加载资源的场景
|
||||
- 初始化失败时抛出异常并进入 `FailedInitialization` 阶段
|
||||
|
||||
使用示例:
|
||||
```csharp
|
||||
var architecture = new GameArchitecture();
|
||||
await architecture.InitializeAsync(); // 异步等待初始化完成
|
||||
```
|
||||
|
||||
优势:
|
||||
- 支持异步初始化 Model 和 System
|
||||
- 可以利用异步 I/O 操作(如异步加载数据)
|
||||
- 提高初始化性能
|
||||
- 不会阻塞主线程
|
||||
|
||||
#### 模块管理
|
||||
|
||||
**InstallModule(IArchitectureModule module)**
|
||||
|
||||
安装架构模块,用于扩展架构功能。
|
||||
```csharp
|
||||
public IArchitectureModule InstallModule(IArchitectureModule module)
|
||||
```
|
||||
|
||||
**返回值:** 返回安装的模块实例
|
||||
|
||||
**特点:**
|
||||
|
||||
- 模块安装时会自动注册生命周期钩子
|
||||
- 模块可以注册额外的组件到架构中
|
||||
- 只能在架构进入 Ready 阶段之前安装模块
|
||||
|
||||
参数:
|
||||
|
||||
- `module`:要安装的模块实例
|
||||
|
||||
使用示例:
|
||||
实现 `IArchitectureLifecycleHook` 接口可以在阶段变化时执行自定义逻辑:
|
||||
|
||||
```csharp
|
||||
// 定义模块
|
||||
public class NetworkModule : IArchitectureModule
|
||||
{
|
||||
public void Install(IArchitecture architecture)
|
||||
{
|
||||
// 注册网络相关的 System 和 Utility
|
||||
architecture.RegisterSystem(new NetworkSystem());
|
||||
architecture.RegisterUtility(new HttpClientUtility());
|
||||
}
|
||||
}
|
||||
|
||||
// 安装模块
|
||||
var architecture = new GameArchitecture();
|
||||
var installedModule = architecture.InstallModule(new NetworkModule());
|
||||
```
|
||||
|
||||
#### 生命周期钩子
|
||||
|
||||
**RegisterLifecycleHook(IArchitectureLifecycle hook)**
|
||||
|
||||
注册生命周期钩子,用于在架构阶段变化时执行自定义逻辑。
|
||||
```csharp
|
||||
public IArchitectureLifecycle RegisterLifecycleHook(IArchitectureLifecycle hook)
|
||||
```
|
||||
|
||||
**返回值:** 返回注册的生命周期钩子实例
|
||||
|
||||
**特点:**
|
||||
|
||||
- 生命周期钩子可以监听所有架构阶段变化
|
||||
- 只能在架构进入 Ready 阶段之前注册
|
||||
- 架构会按注册顺序通知所有钩子
|
||||
|
||||
参数:
|
||||
|
||||
- `hook`:生命周期钩子实例
|
||||
|
||||
使用示例:
|
||||
|
||||
```csharp
|
||||
// 定义生命周期钩子
|
||||
public class PerformanceMonitorHook : IArchitectureLifecycle
|
||||
public class MyLifecycleHook : IArchitectureLifecycleHook
|
||||
{
|
||||
public void OnPhase(ArchitecturePhase phase, IArchitecture architecture)
|
||||
{
|
||||
switch (phase)
|
||||
{
|
||||
case ArchitecturePhase.BeforeModelInit:
|
||||
Console.WriteLine("开始监控 Model 初始化性能");
|
||||
break;
|
||||
case ArchitecturePhase.AfterModelInit:
|
||||
Console.WriteLine("Model 初始化完成,停止监控");
|
||||
break;
|
||||
case ArchitecturePhase.Ready:
|
||||
Console.WriteLine("架构就绪,开始性能统计");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 注册生命周期钩子
|
||||
var architecture = new GameArchitecture();
|
||||
var registeredHook = architecture.RegisterLifecycleHook(new PerformanceMonitorHook());
|
||||
architecture.Initialize();
|
||||
```
|
||||
|
||||
**注意:** 生命周期钩子只能在架构进入 Ready 阶段之前注册。
|
||||
|
||||
#### 属性
|
||||
|
||||
**CurrentPhase**
|
||||
|
||||
获取当前架构的阶段。
|
||||
```csharp
|
||||
public ArchitecturePhase CurrentPhase { get; private set; }
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 只读属性,外部无法直接修改
|
||||
- 实时反映架构的当前状态
|
||||
- 可用于条件判断和状态检查
|
||||
|
||||
使用示例:
|
||||
|
||||
```csharp
|
||||
var architecture = new GameArchitecture();
|
||||
|
||||
// 检查架构是否已就绪
|
||||
if (architecture.CurrentPhase == ArchitecturePhase.Ready)
|
||||
{
|
||||
Console.WriteLine("架构已就绪,可以开始游戏");
|
||||
}
|
||||
|
||||
// 在异步操作中检查阶段变化
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
while (architecture.CurrentPhase != ArchitecturePhase.Ready)
|
||||
{
|
||||
Console.WriteLine($"当前阶段: {architecture.CurrentPhase}");
|
||||
await Task.Delay(100);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**Context**
|
||||
|
||||
获取架构上下文,提供对架构服务的访问。
|
||||
```csharp
|
||||
public IArchitectureContext Context { get; }
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 提供对架构核心服务的访问
|
||||
- 包含事件总线、命令总线、查询总线等
|
||||
- 是架构内部服务的统一入口
|
||||
|
||||
使用示例:
|
||||
|
||||
```csharp
|
||||
// 通过 Context 访问服务
|
||||
var context = architecture.Context;
|
||||
var eventBus = context.EventBus;
|
||||
var commandBus = context.CommandBus;
|
||||
var queryBus = context.QueryBus;
|
||||
var environment = context.Environment;
|
||||
```
|
||||
|
||||
#### 高级特性
|
||||
|
||||
```csharp
|
||||
// 1. 使用自定义配置
|
||||
var config = new ArchitectureConfiguration
|
||||
{
|
||||
ArchitectureProperties = new ArchitectureProperties
|
||||
{
|
||||
StrictPhaseValidation = true, // 启用严格阶段验证
|
||||
AllowLateRegistration = false // 禁止就绪后注册组件
|
||||
}
|
||||
};
|
||||
var architecture = new GameArchitecture(configuration: config);
|
||||
|
||||
// 2. 模块安装
|
||||
var module = new GameModule();
|
||||
architecture.InstallModule(module);
|
||||
|
||||
// 3. 监听架构阶段变化
|
||||
public class GamePhaseListener : IArchitecturePhaseAware
|
||||
{
|
||||
public void OnArchitecturePhase(ArchitecturePhase phase)
|
||||
{
|
||||
switch (phase)
|
||||
{
|
||||
case ArchitecturePhase.Ready:
|
||||
Console.WriteLine("架构已就绪,可以开始游戏了");
|
||||
Console.WriteLine("Architecture is ready!");
|
||||
break;
|
||||
case ArchitecturePhase.Destroying:
|
||||
Console.WriteLine("架构正在销毁");
|
||||
Console.WriteLine("Architecture is being destroyed!");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 生命周期钩子
|
||||
public class LifecycleHook : IArchitectureLifecycle
|
||||
{
|
||||
public void OnPhase(ArchitecturePhase phase, IArchitecture architecture)
|
||||
{
|
||||
Console.WriteLine($"架构阶段变化: {phase}");
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 等待架构就绪
|
||||
public async Task WaitForArchitectureReady()
|
||||
{
|
||||
var architecture = new GameArchitecture();
|
||||
var initTask = architecture.InitializeAsync();
|
||||
|
||||
// 可以在其他地方等待架构就绪
|
||||
await architecture.WaitUntilReadyAsync();
|
||||
Console.WriteLine("架构已就绪");
|
||||
}
|
||||
// 注册钩子
|
||||
architecture.RegisterLifecycleHook(new MyLifecycleHook());
|
||||
```
|
||||
|
||||
### ArchitectureConfiguration 架构配置类
|
||||
### 初始化流程
|
||||
|
||||
架构配置类,用于配置架构的行为。
|
||||
```
|
||||
1. 创建 Architecture 实例
|
||||
└─> 构造函数初始化管理器
|
||||
|
||||
**主要配置项:**
|
||||
2. 调用 InitializeAsync() 或 Initialize()
|
||||
├─> 初始化环境 (Environment.Initialize())
|
||||
├─> 注册内置服务模块
|
||||
├─> 初始化架构上下文
|
||||
├─> 执行服务钩子
|
||||
├─> 初始化服务模块
|
||||
├─> 调用 OnInitialize() (用户注册组件)
|
||||
├─> 初始化所有组件
|
||||
│ ├─> BeforeUtilityInit → 初始化 Utility → AfterUtilityInit
|
||||
│ ├─> BeforeModelInit → 初始化 Model → AfterModelInit
|
||||
│ └─> BeforeSystemInit → 初始化 System → AfterSystemInit
|
||||
├─> 冻结 IoC 容器
|
||||
└─> 进入 Ready 阶段
|
||||
|
||||
```csharp
|
||||
public class ArchitectureConfiguration : IArchitectureConfiguration
|
||||
{
|
||||
public IArchitectureProperties ArchitectureProperties { get; set; } = new ArchitectureProperties();
|
||||
public IEnvironmentProperties EnvironmentProperties { get; set; } = new EnvironmentProperties();
|
||||
public ILoggerProperties LoggerProperties { get; set; } = new LoggerProperties();
|
||||
}
|
||||
|
||||
public class ArchitectureProperties
|
||||
{
|
||||
public bool StrictPhaseValidation { get; set; } = false; // 严格阶段验证
|
||||
public bool AllowLateRegistration { get; set; } = true; // 允许延迟注册
|
||||
}
|
||||
3. 等待就绪 (可选)
|
||||
└─> await architecture.WaitUntilReadyAsync()
|
||||
```
|
||||
|
||||
**使用示例:**
|
||||
### 销毁流程
|
||||
|
||||
```csharp
|
||||
var config = new ArchitectureConfiguration
|
||||
{
|
||||
ArchitectureProperties = new ArchitectureProperties
|
||||
{
|
||||
StrictPhaseValidation = true, // 启用严格阶段验证
|
||||
AllowLateRegistration = false // 禁止就绪后注册组件
|
||||
},
|
||||
LoggerProperties = new LoggerProperties
|
||||
{
|
||||
LoggerFactoryProvider = new ConsoleLoggerFactoryProvider() // 自定义日志工厂
|
||||
}
|
||||
};
|
||||
|
||||
var architecture = new GameArchitecture(configuration: config);
|
||||
```
|
||||
|
||||
### ArchitectureServices 架构服务类
|
||||
|
||||
架构服务类,管理命令总线、查询总线、IOC容器和类型事件系统。
|
||||
|
||||
**核心服务:**
|
||||
|
||||
- `IIocContainer Container`:依赖注入容器
|
||||
- `IEventBus EventBus`:事件总线
|
||||
- `ICommandBus CommandBus`:命令总线
|
||||
- `IQueryBus QueryBus`:查询总线
|
||||
|
||||
### ArchitectureContext 架构上下文类
|
||||
|
||||
架构上下文类,提供对架构服务的访问。
|
||||
|
||||
**功能:**
|
||||
|
||||
- 统一访问架构核心服务
|
||||
- 管理服务实例的生命周期
|
||||
- 提供服务解析功能
|
||||
|
||||
### GameContext 游戏上下文类
|
||||
|
||||
游戏上下文类,管理架构上下文与类型的绑定关系。
|
||||
|
||||
**功能:**
|
||||
|
||||
- 维护架构类型与上下文实例的映射
|
||||
- 提供全局上下文访问
|
||||
- 支持多架构实例管理
|
||||
|
||||
## 设计模式
|
||||
|
||||
### 1. 依赖注入
|
||||
|
||||
通过构造函数注入或容器解析获取架构实例。
|
||||
|
||||
### 2. 控制反转 (IoC)
|
||||
|
||||
使用内置 IoC 容器管理组件生命周期和依赖关系。
|
||||
|
||||
### 3. 命令模式
|
||||
|
||||
通过 `ICommand` 封装所有用户操作。
|
||||
|
||||
### 4. 查询模式 (CQRS)
|
||||
|
||||
通过 `IQuery<T>` 分离查询和命令操作。
|
||||
|
||||
### 5. 观察者模式
|
||||
|
||||
通过事件系统实现组件间的松耦合通信。
|
||||
|
||||
### 6. 阶段式生命周期管理
|
||||
|
||||
通过 `ArchitecturePhase` 枚举和生命周期钩子管理架构状态。
|
||||
|
||||
### 7. 组合优于继承
|
||||
|
||||
通过接口组合获得不同能力,而不是深层继承链。
|
||||
|
||||
### 8. 模块化设计
|
||||
|
||||
通过 `IArchitectureModule` 实现架构的可扩展性。
|
||||
|
||||
### 9. 工厂模式
|
||||
|
||||
通过配置对象和工厂方法创建架构实例。
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **保持架构类简洁**:只在 `Init()` 中注册组件,不要包含业务逻辑
|
||||
2. **合理划分职责**:
|
||||
- Model:数据和状态
|
||||
- System:业务逻辑和规则
|
||||
- Utility:无状态的工具方法
|
||||
3. **使用依赖注入**:通过构造函数注入架构实例,便于测试
|
||||
4. **事件命名规范**:使用过去式命名事件类,如 `PlayerDiedEvent`
|
||||
5. **避免循环依赖**:System 不应直接引用 System,应通过事件通信
|
||||
6. **使用模块扩展**:通过 `IArchitectureModule` 实现架构的可扩展性
|
||||
7. **Core 模块与平台解耦**:GFramework.Core 不包含 Godot 相关代码,Godot 集成在单独模块中
|
||||
8. **合理配置阶段验证**:根据项目需求配置 `StrictPhaseValidation` 和 `AllowLateRegistration`
|
||||
9. **及时处理初始化异常**:捕获并处理架构初始化过程中的异常
|
||||
10. **使用异步初始化**:对于需要加载大量资源的场景,优先使用 `InitializeAsync()`
|
||||
|
||||
## 相关包
|
||||
|
||||
- **command** - 命令模式实现
|
||||
- **query** - 查询模式实现
|
||||
- **events** - 事件系统
|
||||
- **ioc** - IoC 容器
|
||||
- **model** - 数据模型
|
||||
- **system** - 业务系统
|
||||
- **utility** - 工具类
|
||||
- **GFramework.Godot** - Godot 特定集成(GodotNode 扩展、GodotLogger 等)
|
||||
- **extensions** - 扩展方法
|
||||
- **logging** - 日志系统
|
||||
- **environment** - 环境管理
|
||||
1. 调用 DestroyAsync() 或 Destroy()
|
||||
├─> 检查当前阶段 (如果是 None 或已销毁则直接返回)
|
||||
├─> 进入 Destroying 阶段
|
||||
├─> 逆序销毁所有组件
|
||||
│ ├─> 优先调用 IAsyncDestroyable.DestroyAsync()
|
||||
│ └─> 否则调用 IDestroyable.Destroy()
|
||||
├─> 销毁服务模块
|
||||
├─> 清空 IoC 容器
|
||||
└─> 进入 Destroyed 阶段
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**许可证**:Apache 2.0
|
||||
**版本**: 1.1.0
|
||||
**更新日期**: 2026-03-17
|
||||
**相关文档**:
|
||||
|
||||
- [核心框架概述](./index.md)
|
||||
- [ADR-001: 拆分 Architecture 核心类](/docs/adr/001-split-architecture-class.md)
|
||||
|
||||
@ -65,15 +65,48 @@ Event ──┘
|
||||
|
||||
### 架构阶段
|
||||
|
||||
框架提供了精细化的生命周期管理,包含 11 个阶段:
|
||||
|
||||
```
|
||||
初始化:Init → BeforeUtilityInit → AfterUtilityInit → BeforeModelInit → AfterModelInit → BeforeSystemInit → AfterSystemInit → Ready
|
||||
销毁:Destroy → Destroying → Destroyed
|
||||
初始化流程:
|
||||
None → BeforeUtilityInit → AfterUtilityInit → BeforeModelInit → AfterModelInit → BeforeSystemInit → AfterSystemInit → Ready
|
||||
|
||||
销毁流程:
|
||||
Ready → Destroying → Destroyed
|
||||
|
||||
异常流程:
|
||||
Any → FailedInitialization
|
||||
```
|
||||
|
||||
每个阶段都会触发 `PhaseChanged` 事件,允许组件监听架构状态变化。
|
||||
|
||||
## 架构图
|
||||
|
||||
### 整体架构
|
||||
|
||||
从 v1.1.0 开始,Architecture 类采用模块化设计,将职责分离到专门的管理器中:
|
||||
|
||||
```
|
||||
┌──────────────────┐
|
||||
│ Architecture │ ← 核心协调器
|
||||
└────────┬─────────┘
|
||||
│
|
||||
┌────────────────────┼────────────────────┐
|
||||
│ │ │
|
||||
┌────▼────────┐ ┌──────▼──────┐ ┌────────▼────────┐
|
||||
│ Lifecycle │ │ Component │ │ Modules │
|
||||
│ Manager │ │ Registry │ │ Manager │
|
||||
└─────────────┘ └─────────────┘ └─────────────────┘
|
||||
│ │ │
|
||||
│ │ │
|
||||
生命周期管理 组件注册管理 模块管理
|
||||
- 阶段转换 - System 注册 - 模块安装
|
||||
- 钩子管理 - Model 注册 - 行为注册
|
||||
- 初始化/销毁 - Utility 注册
|
||||
```
|
||||
|
||||
这种设计遵循单一职责原则,使代码更易维护和测试。详见 [ADR-001](/docs/adr/001-split-architecture-class.md)。
|
||||
|
||||
```
|
||||
┌──────────────────┐
|
||||
│ Architecture │ ← 管理所有组件
|
||||
@ -284,6 +317,93 @@ public class PlayerController : IController
|
||||
|
||||
## 包说明
|
||||
|
||||
### Architecture 内部结构 (v1.1.0+)
|
||||
|
||||
从 v1.1.0 开始,Architecture 类采用模块化设计,将原本 708 行的单一类拆分为 4 个职责清晰的类:
|
||||
|
||||
#### 1. Architecture (核心协调器)
|
||||
|
||||
**职责**: 提供统一的公共 API,协调各个管理器
|
||||
|
||||
**主要方法**:
|
||||
|
||||
- `RegisterSystem<T>()` - 注册系统
|
||||
- `RegisterModel<T>()` - 注册模型
|
||||
- `RegisterUtility<T>()` - 注册工具
|
||||
- `InstallModule()` - 安装模块
|
||||
- `InitializeAsync()` / `Initialize()` - 初始化架构
|
||||
- `DestroyAsync()` / `Destroy()` - 销毁架构
|
||||
|
||||
**事件**:
|
||||
|
||||
- `PhaseChanged` - 阶段变更事件
|
||||
|
||||
#### 2. ArchitectureLifecycle (生命周期管理器)
|
||||
|
||||
**职责**: 管理架构的生命周期和阶段转换
|
||||
|
||||
**核心功能**:
|
||||
|
||||
- 11 个架构阶段的管理和转换
|
||||
- 生命周期钩子 (IArchitectureLifecycleHook) 管理
|
||||
- 组件初始化 (按 Utility → Model → System 顺序)
|
||||
- 组件销毁 (逆序销毁)
|
||||
- 就绪状态管理
|
||||
|
||||
**关键方法**:
|
||||
|
||||
- `EnterPhase()` - 进入指定阶段
|
||||
- `RegisterLifecycleHook()` - 注册生命周期钩子
|
||||
- `InitializeAllComponentsAsync()` - 初始化所有组件
|
||||
- `DestroyAsync()` - 异步销毁
|
||||
|
||||
#### 3. ArchitectureComponentRegistry (组件注册管理器)
|
||||
|
||||
**职责**: 管理 System、Model、Utility 的注册
|
||||
|
||||
**核心功能**:
|
||||
|
||||
- 组件注册和验证
|
||||
- 自动设置组件上下文 (IContextAware)
|
||||
- 自动注册组件生命周期 (IInitializable、IDestroyable)
|
||||
- 支持实例注册和类型注册
|
||||
|
||||
**关键方法**:
|
||||
|
||||
- `RegisterSystem<T>()` - 注册系统
|
||||
- `RegisterModel<T>()` - 注册模型
|
||||
- `RegisterUtility<T>()` - 注册工具
|
||||
|
||||
#### 4. ArchitectureModules (模块管理器)
|
||||
|
||||
**职责**: 管理架构模块和中介行为
|
||||
|
||||
**核心功能**:
|
||||
|
||||
- 模块安装 (IArchitectureModule)
|
||||
- 中介行为注册 (Mediator Behaviors)
|
||||
|
||||
**关键方法**:
|
||||
|
||||
- `InstallModule()` - 安装模块
|
||||
- `RegisterMediatorBehavior<T>()` - 注册中介行为
|
||||
|
||||
#### 设计优势
|
||||
|
||||
这种模块化设计带来以下优势:
|
||||
|
||||
1. **单一职责**: 每个类只负责一个明确的功能
|
||||
2. **易于测试**: 可以独立测试每个管理器
|
||||
3. **易于维护**: 修改某个功能不影响其他功能
|
||||
4. **易于扩展**: 添加新功能更容易
|
||||
5. **代码安全**: 消除了 `null!` 断言,所有字段在构造后立即可用
|
||||
|
||||
详细的设计决策请参考 [ADR-001: 拆分 Architecture 核心类](/docs/adr/001-split-architecture-class.md)。
|
||||
|
||||
---
|
||||
|
||||
## 包说明
|
||||
|
||||
| 包名 | 职责 | 文档 |
|
||||
|------------------|-----------------|----------------------|
|
||||
| **architecture** | 架构核心,管理所有组件生命周期 | [查看](./architecture) |
|
||||
@ -308,12 +428,25 @@ public class PlayerController : IController
|
||||
|
||||
```
|
||||
创建 Architecture 实例
|
||||
└─> Init()
|
||||
├─> RegisterModel → Model.SetContext() → Model.Init()
|
||||
├─> RegisterSystem → System.SetContext() → System.Init()
|
||||
└─> RegisterUtility → Utility 注册到容器
|
||||
└─> 构造函数
|
||||
├─> 初始化 Logger
|
||||
├─> 创建 ArchitectureLifecycle
|
||||
├─> 创建 ArchitectureComponentRegistry
|
||||
└─> 创建 ArchitectureModules
|
||||
└─> InitializeAsync()
|
||||
├─> OnInitialize() (用户注册组件)
|
||||
│ ├─> RegisterModel → Model.SetContext()
|
||||
│ ├─> RegisterSystem → System.SetContext()
|
||||
│ └─> RegisterUtility → 注册到容器
|
||||
└─> InitializeAllComponentsAsync()
|
||||
├─> BeforeUtilityInit → Utility.Initialize()
|
||||
├─> BeforeModelInit → Model.Initialize()
|
||||
├─> BeforeSystemInit → System.Initialize()
|
||||
└─> Ready
|
||||
```
|
||||
|
||||
**重要变更 (v1.1.0)**: 管理器现在在构造函数中初始化,而不是在 InitializeAsync 中。这消除了 `null!` 断言,提高了代码安全性。
|
||||
|
||||
### 2. Command 执行流程
|
||||
|
||||
```
|
||||
@ -503,5 +636,21 @@ public interface IController :
|
||||
|
||||
---
|
||||
|
||||
**版本**: 1.0.0
|
||||
**许可证**: Apache 2.0
|
||||
**版本**: 1.1.0
|
||||
**更新日期**: 2026-03-17
|
||||
**许可证**: Apache 2.0
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.1.0 (2026-03-17)
|
||||
|
||||
**重大重构**:
|
||||
|
||||
- 拆分 Architecture 类为 4 个职责清晰的类
|
||||
- 消除 3 处 `null!` 强制断言,提高代码安全性
|
||||
- 在构造函数中初始化管理器,符合"构造即完整"原则
|
||||
- 添加 `PhaseChanged` 事件,支持阶段监听
|
||||
|
||||
**向后兼容**: 所有公共 API 保持不变,现有代码无需修改。
|
||||
|
||||
详见 [ADR-001: 拆分 Architecture 核心类](/docs/adr/001-split-architecture-class.md)
|
||||
@ -189,7 +189,7 @@ public class GameArchitecture : Architecture
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ 使用 IOC 容器注册
|
||||
// ✅ 使用 IoC 容器注册
|
||||
protected override void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IPlayerService, PlayerService>();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user