Skip to content
English

CQRS 请求、通知与流 ​

接入 ​

安装 GeWuYou.GFramework.Cqrs,在组合根调用 AddCqrsRuntime。处理器通过构造函数接收依赖,消费方取得 ICqrsRuntime 后选择入口:

任务调用
请求一个响应SendAsync
通知多个处理器PublishAsync
读取多个异步结果CreateStream

需要生成注册表时,在声明处理器的项目中同时安装运行时和源码生成器。对运行时才取得的程序集,使用 AddCqrsHandlersFromAssembly。传入调用方的取消令牌。

管道与作用域 ​

按外层到内层的顺序登记管道行为。为依赖 scoped 对象的行为使用 scoped 生命周期,并在同一调用方作用域解析 runtime;流式调用的作用域覆盖完整枚举。

cs
var services = new ServiceCollection();
services.AddScopedCqrsRuntime();
services.AddScoped<RequestScope>();
services.AddCqrsHandlers(GFramework.Generated.Cqrs.CqrsRegistration.CreateRegistry());
// Open generic behavior mapping follows the request/response parameter order.
services.AddCqrsPipelineBehavior(typeof(LoggingBehavior<,>));
services.AddCqrsPipelineBehavior(typeof(ScopeBehavior<,>), ServiceLifetime.Scoped);

var provider = services.BuildServiceProvider(
    new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true });
await using var providerLifetime = provider.ConfigureAwait(false);
RequestScope state;
var scope = provider.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
    state = scope.ServiceProvider.GetRequiredService<RequestScope>();
    var runtime = scope.ServiceProvider.GetRequiredService<ICqrsRuntime>();
    if (await runtime.SendAsync(new GetLength("Alice")).ConfigureAwait(false) != 5 || state.Calls != 1 || state.Disposed)
        throw new InvalidOperationException("The generated handler or scoped behavior failed.");
}
if (!state.Disposed)
    throw new InvalidOperationException("The caller scope did not release its dependency.");
Console.WriteLine("CQRS_PIPELINE_PASS");
bash
dotnet run --project Samples/CqrsPipelineDemo -c Release

输出 CQRS_PIPELINE_PASS 表示处理器已返回响应,作用域已释放。另见处理器注册表生成器。

Apache 2.0 许可证