using System.Collections.Concurrent;
using GFramework.Core.Abstractions.Architecture;
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 Mediator;
using ICommand = GFramework.Core.Abstractions.Command.ICommand;
namespace GFramework.Core.Architectures;
///
/// 架构上下文类,提供对系统、模型、工具等组件的访问以及命令、查询、事件的执行管理
///
public class ArchitectureContext(IIocContainer container) : IArchitectureContext
{
private readonly IIocContainer _container = container ?? throw new ArgumentNullException(nameof(container));
private readonly ConcurrentDictionary _serviceCache = new();
#region Mediator Integration
///
/// 获取 Mediator 实例(延迟加载)
///
private IMediator Mediator => GetOrCache();
///
/// 获取 ISender 实例(更轻量的发送器)
///
private ISender Sender => GetOrCache();
///
/// 获取 IPublisher 实例(用于发布通知)
///
private IPublisher Publisher => GetOrCache();
///
/// 获取指定类型的服务实例,如果缓存中存在则直接返回,否则从容器中获取并缓存
///
/// 服务类型,必须为引用类型
/// 服务实例,如果不存在则抛出异常
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"));
}
///
/// [Mediator] 发送请求(Command/Query)
/// 这是推荐的新方式,统一处理命令和查询
///
/// 响应类型
/// 请求对象(Command 或 Query)
/// 取消令牌
/// 响应结果
/// 当 Mediator 未注册时抛出
public async ValueTask SendRequestAsync(
IRequest request,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var mediator = Mediator;
if (mediator == null)
throw new InvalidOperationException(
"Mediator not registered. Call EnableMediator() in your Architecture.OnInitialize() method.");
return await mediator.Send(request, cancellationToken);
}
///
/// [Mediator] 发送请求的同步版本(不推荐,仅用于兼容性)
///
/// 响应类型
/// 请求对象
/// 响应结果
public TResponse SendRequest(IRequest request)
{
return SendRequestAsync(request).AsTask().GetAwaiter().GetResult();
}
///
/// [Mediator] 发布通知(一对多)
/// 用于事件驱动场景,多个处理器可以同时处理同一个通知
///
/// 通知类型
/// 通知对象
/// 取消令牌
public async ValueTask PublishAsync(
TNotification notification,
CancellationToken cancellationToken = default)
where TNotification : INotification
{
ArgumentNullException.ThrowIfNull(notification);
var publisher = Publisher;
if (publisher == null)
throw new InvalidOperationException("Publisher not registered.");
await publisher.Publish(notification, cancellationToken);
}
///
/// [Mediator] 发送请求并返回流(用于大数据集)
///
/// 响应项类型
/// 流式请求
/// 取消令牌
/// 异步流
public IAsyncEnumerable CreateStream(
IStreamRequest request,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var mediator = Mediator;
if (mediator == null)
throw new InvalidOperationException("Mediator not registered.");
return mediator.CreateStream(request, cancellationToken);
}
///
/// [扩展] 发送命令(无返回值)
/// 语法糖,等同于 SendRequestAsync<Unit>
///
public async ValueTask SendAsync(
TCommand command,
CancellationToken cancellationToken = default)
where TCommand : IRequest
{
await SendRequestAsync(command, cancellationToken);
}
///
/// [扩展] 发送命令(有返回值)
/// 语法糖,等同于 SendRequestAsync<TResponse>
///
public async ValueTask SendAsync(
IRequest command,
CancellationToken cancellationToken = default)
{
return await SendRequestAsync(command, cancellationToken);
}
#endregion
#region Query Execution
///
/// 发送一个查询请求
///
/// 查询结果类型
/// 要发送的查询
/// 查询结果
public TResult SendQuery(Abstractions.Query.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);
}
///
/// [Mediator] 发送查询的同步版本(不推荐,仅用于兼容性)
///
/// 查询响应类型
/// 要发送的查询对象
/// 查询结果
public TResponse SendQuery(Mediator.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);
}
///
/// [Mediator] 异步发送查询并返回结果
/// 通过Mediator模式发送查询请求,支持取消操作
///
/// 查询响应类型
/// 要发送的查询对象
/// 取消令牌,用于取消操作
/// 包含查询结果的ValueTask
public async ValueTask SendQueryAsync(Mediator.IQuery query,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var sender = Sender;
if (sender == null)
throw new InvalidOperationException("Sender not registered.");
return await sender.Send(query, cancellationToken);
}
#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
///
/// [Mediator] 异步发送命令并返回结果
/// 通过Mediator模式发送命令请求,支持取消操作
///
/// 命令响应类型
/// 要发送的命令对象
/// 取消令牌,用于取消操作
/// 包含命令执行结果的ValueTask
public async ValueTask SendCommandAsync(Mediator.ICommand command,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(command);
var sender = Sender;
if (sender == null)
throw new InvalidOperationException("Sender not registered.");
return await sender.Send(command, cancellationToken);
}
///
/// 发送并异步执行一个命令请求
///
/// 要发送的命令
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);
}
///
/// 发送并异步执行一个带返回值的命令请求
///
/// 命令执行结果类型
/// 要发送的命令
/// 命令执行结果
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);
}
///
/// [Mediator] 发送命令的同步版本(不推荐,仅用于兼容性)
///
/// 命令响应类型
/// 要发送的命令对象
/// 命令执行结果
public TResponse SendCommand(Mediator.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(Abstractions.Command.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
}