using System.Collections.Concurrent; using GFramework.Core.Abstractions.Architectures; using GFramework.Core.Abstractions.Command; using GFramework.Core.Abstractions.Environment; using GFramework.Core.Abstractions.Events; using GFramework.Core.Abstractions.Ioc; using GFramework.Core.Abstractions.Model; using GFramework.Core.Abstractions.Query; using GFramework.Core.Abstractions.Systems; using GFramework.Core.Abstractions.Utility; using GFramework.Cqrs.Abstractions.Cqrs; using ICommand = GFramework.Core.Abstractions.Command.ICommand; namespace GFramework.Core.Architectures; /// /// 架构上下文类,提供对系统、模型、工具等组件的访问以及命令、查询、事件的执行管理 /// public class ArchitectureContext : IArchitectureContext { private readonly IIocContainer _container; private readonly Lazy _cqrsRuntime; private readonly ConcurrentDictionary _serviceCache = new(); /// /// 初始化新的架构上下文,并绑定其依赖容器。 /// /// /// 当前架构使用的 IOC 容器。 /// CQRS runtime 与其他框架服务会通过该容器延迟解析,以避免在上下文构造阶段强制拉起整条运行时链路。 /// /// public ArchitectureContext(IIocContainer container) { _container = container ?? throw new ArgumentNullException(nameof(container)); _cqrsRuntime = new Lazy( ResolveCqrsRuntime, LazyThreadSafetyMode.ExecutionAndPublication); } #region CQRS Integration /// /// 获取 CQRS runtime seam。 /// /// /// 该实例会在首次访问时从容器解析,并通过 保证并发场景下只执行一次初始化, /// 避免多个请求线程重复触发同一个 runtime 的容器解析。 /// private ICqrsRuntime CqrsRuntime => _cqrsRuntime.Value; /// /// 从容器解析当前架构上下文依赖的 CQRS runtime。 /// /// 已注册的 CQRS runtime 实例。 /// 容器中未注册 private ICqrsRuntime ResolveCqrsRuntime() { return _container.Get() ?? throw new InvalidOperationException("ICqrsRuntime not registered"); } /// /// 获取指定类型的服务实例,如果缓存中存在则直接返回,否则从容器中获取并缓存 /// /// 服务类型,必须为引用类型 /// 服务实例,如果不存在则抛出异常 public TService GetService() where TService : class { return GetOrCache(); } /// /// 从缓存中获取或创建指定类型的服务实例 /// 首先尝试从缓存中获取服务实例,如果缓存中不存在则从容器中获取并存入缓存 /// /// 服务类型,必须为引用类型 /// 服务实例,如果不存在则抛出异常 private TService GetOrCache() where TService : class { return (TService)_serviceCache.GetOrAdd( typeof(TService), _ => _container.Get() ?? throw new InvalidOperationException( $"Service {typeof(TService)} not registered")); } /// /// 发送请求(Command/Query) /// 使用 GFramework 自有 CQRS runtime 统一处理命令和查询。 /// /// 响应类型 /// 请求对象(Command 或 Query) /// 取消令牌 /// 响应结果 public async ValueTask SendRequestAsync( IRequest request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(request); return await CqrsRuntime.SendAsync(this, request, cancellationToken).ConfigureAwait(false); } /// /// 发送请求的同步版本(不推荐,仅用于兼容性) /// /// 响应类型 /// 请求对象 /// 响应结果 public TResponse SendRequest(IRequest request) { return SendRequestAsync(request).AsTask().GetAwaiter().GetResult(); } /// /// 发布通知(一对多) /// 使用 GFramework 自有 CQRS runtime 分发到所有已注册通知处理器。 /// /// 通知类型 /// 通知对象 /// 取消令牌 public async ValueTask PublishAsync( TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification { ArgumentNullException.ThrowIfNull(notification); await CqrsRuntime.PublishAsync(this, notification, cancellationToken).ConfigureAwait(false); } /// /// 发送请求并返回流(用于大数据集) /// /// 响应项类型 /// 流式请求 /// 取消令牌 /// 异步流 public IAsyncEnumerable CreateStream( IStreamRequest request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(request); return CqrsRuntime.CreateStream(this, request, cancellationToken); } /// /// [扩展] 发送命令(无返回值) /// 语法糖,等同于 SendRequestAsync<Unit> /// public async ValueTask SendAsync( TCommand command, CancellationToken cancellationToken = default) where TCommand : IRequest { await SendRequestAsync(command, cancellationToken).ConfigureAwait(false); } /// /// [扩展] 发送命令(有返回值) /// 语法糖,等同于 SendRequestAsync<TResponse> /// public async ValueTask SendAsync( IRequest command, CancellationToken cancellationToken = default) { return await SendRequestAsync(command, cancellationToken).ConfigureAwait(false); } #endregion #region Query Execution /// /// 发送一个查询请求 /// /// 查询结果类型 /// 要发送的查询 /// 查询结果 public TResult SendQuery(IQuery query) { if (query == null) throw new ArgumentNullException(nameof(query)); var queryBus = GetOrCache(); if (queryBus == null) throw new InvalidOperationException("IQueryExecutor not registered"); return queryBus.Send(query); } /// /// 发送 CQRS 查询的同步版本(不推荐,仅用于兼容性) /// /// 查询响应类型 /// 要发送的查询对象 /// 查询结果 public TResponse SendQuery(Cqrs.Abstractions.Cqrs.Query.IQuery query) { return SendQueryAsync(query).AsTask().GetAwaiter().GetResult(); } /// /// 异步发送一个查询请求 /// /// 查询结果类型 /// 要发送的异步查询 /// 查询结果 public async Task SendQueryAsync(IAsyncQuery query) { if (query == null) throw new ArgumentNullException(nameof(query)); var asyncQueryBus = GetOrCache(); if (asyncQueryBus == null) throw new InvalidOperationException("IAsyncQueryExecutor not registered"); return await asyncQueryBus.SendAsync(query).ConfigureAwait(false); } /// /// 异步发送 CQRS 查询并返回结果。 /// /// 查询响应类型 /// 要发送的查询对象 /// 取消令牌,用于取消操作 /// 包含查询结果的ValueTask public async ValueTask SendQueryAsync(Cqrs.Abstractions.Cqrs.Query.IQuery query, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); return await SendRequestAsync(query, cancellationToken).ConfigureAwait(false); } #endregion #region Component Retrieval /// /// 获取指定类型的所有服务实例 /// /// 服务类型 /// 所有符合条件的服务实例列表 public IReadOnlyList GetServices() where TService : class { return _container.GetAll(); } /// /// 从IOC容器中获取指定类型的系统实例 /// /// 目标系统类型 /// 对应的系统实例 public TSystem GetSystem() where TSystem : class, ISystem { return GetService(); } /// /// 获取指定类型的所有系统实例 /// /// 系统类型 /// 所有符合条件的系统实例列表 public IReadOnlyList GetSystems() where TSystem : class, ISystem { return _container.GetAll(); } /// /// 从IOC容器中获取指定类型的模型实例 /// /// 目标模型类型 /// 对应的模型实例 public TModel GetModel() where TModel : class, IModel { return GetService(); } /// /// 获取指定类型的所有模型实例 /// /// 模型类型 /// 所有符合条件的模型实例列表 public IReadOnlyList GetModels() where TModel : class, IModel { return _container.GetAll(); } /// /// 从IOC容器中获取指定类型的工具实例 /// /// 目标工具类型 /// 对应的工具实例 public TUtility GetUtility() where TUtility : class, IUtility { return GetService(); } /// /// 获取指定类型的所有工具实例 /// /// 工具类型 /// 所有符合条件的工具实例列表 public IReadOnlyList GetUtilities() where TUtility : class, IUtility { return _container.GetAll(); } /// /// 获取指定类型的所有服务实例,并按优先级排序 /// 实现 IPrioritized 接口的服务将按优先级排序(数值越小优先级越高) /// /// 服务类型 /// 按优先级排序后的服务实例列表 public IReadOnlyList GetServicesByPriority() where TService : class { return _container.GetAllByPriority(); } /// /// 获取指定类型的所有系统实例,并按优先级排序 /// 实现 IPrioritized 接口的系统将按优先级排序(数值越小优先级越高) /// /// 系统类型 /// 按优先级排序后的系统实例列表 public IReadOnlyList GetSystemsByPriority() where TSystem : class, ISystem { return _container.GetAllByPriority(); } /// /// 获取指定类型的所有模型实例,并按优先级排序 /// 实现 IPrioritized 接口的模型将按优先级排序(数值越小优先级越高) /// /// 模型类型 /// 按优先级排序后的模型实例列表 public IReadOnlyList GetModelsByPriority() where TModel : class, IModel { return _container.GetAllByPriority(); } /// /// 获取指定类型的所有工具实例,并按优先级排序 /// 实现 IPrioritized 接口的工具将按优先级排序(数值越小优先级越高) /// /// 工具类型 /// 按优先级排序后的工具实例列表 public IReadOnlyList GetUtilitiesByPriority() where TUtility : class, IUtility { return _container.GetAllByPriority(); } #endregion #region Command Execution /// /// 异步发送 CQRS 命令并返回结果。 /// /// 命令响应类型 /// 要发送的命令对象 /// 取消令牌,用于取消操作 /// 包含命令执行结果的ValueTask public async ValueTask SendCommandAsync( Cqrs.Abstractions.Cqrs.Command.ICommand command, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(command); return await SendRequestAsync(command, cancellationToken).ConfigureAwait(false); } /// /// 发送并异步执行一个命令请求 /// /// 要发送的命令 public async Task SendCommandAsync(IAsyncCommand command) { ArgumentNullException.ThrowIfNull(command); var commandBus = GetOrCache(); if (commandBus == null) throw new InvalidOperationException("ICommandExecutor not registered"); await commandBus.SendAsync(command).ConfigureAwait(false); } /// /// 发送并异步执行一个带返回值的命令请求 /// /// 命令执行结果类型 /// 要发送的命令 /// 命令执行结果 public async Task SendCommandAsync(IAsyncCommand command) { ArgumentNullException.ThrowIfNull(command); var commandBus = GetOrCache(); if (commandBus == null) throw new InvalidOperationException("ICommandExecutor not registered"); return await commandBus.SendAsync(command).ConfigureAwait(false); } /// /// 发送 CQRS 命令的同步版本(不推荐,仅用于兼容性) /// /// 命令响应类型 /// 要发送的命令对象 /// 命令执行结果 public TResponse SendCommand(Cqrs.Abstractions.Cqrs.Command.ICommand command) { return SendCommandAsync(command).AsTask().GetAwaiter().GetResult(); } /// /// 发送一个命令请求 /// /// 要发送的命令 public void SendCommand(ICommand command) { ArgumentNullException.ThrowIfNull(command); var commandBus = GetOrCache(); commandBus.Send(command); } /// /// 发送一个带返回值的命令请求 /// /// 命令执行结果类型 /// 要发送的命令 /// 命令执行结果 public TResult SendCommand(ICommand command) { ArgumentNullException.ThrowIfNull(command); var commandBus = GetOrCache(); if (commandBus == null) throw new InvalidOperationException("ICommandExecutor not registered"); return commandBus.Send(command); } #endregion #region Event Management /// /// 发送一个默认构造的新事件 /// /// 事件类型 public void SendEvent() where TEvent : new() { var eventBus = GetOrCache(); eventBus.Send(); } /// /// 发送一个具体的事件实例 /// /// 事件类型 /// 事件参数 public void SendEvent(TEvent e) where TEvent : class { ArgumentNullException.ThrowIfNull(e); var eventBus = GetOrCache(); eventBus.Send(e); } /// /// 注册事件处理器 /// /// 事件类型 /// 事件处理委托 /// 事件注销接口 public IUnRegister RegisterEvent(Action handler) { ArgumentNullException.ThrowIfNull(handler); var eventBus = GetOrCache(); if (eventBus == null) throw new InvalidOperationException("IEventBus not registered"); return eventBus.Register(handler); } /// /// 取消对某类型事件的监听 /// /// 事件类型 /// 之前绑定的事件处理器 public void UnRegisterEvent(Action onEvent) { ArgumentNullException.ThrowIfNull(onEvent); var eventBus = GetOrCache(); eventBus.UnRegister(onEvent); } /// /// 获取当前环境对象 /// /// 环境对象实例 public IEnvironment GetEnvironment() { var environment = GetOrCache(); return environment ?? throw new InvalidOperationException("IEnvironment not registered"); } #endregion }