CQRS requests, notifications, and streams
Set up the runtime
Install GeWuYou.GFramework.Cqrs and call AddCqrsRuntime in the composition root. Inject dependencies into handlers and resolve ICqrsRuntime in consumers.
| Task | Call |
|---|---|
| Request one response | SendAsync |
| Notify multiple handlers | PublishAsync |
| Read multiple asynchronous results | CreateStream |
To generate a registry, install the runtime and source generator in the project that declares the handlers. For assemblies discovered at runtime, use AddCqrsHandlersFromAssembly. Pass the caller's cancellation token.
Pipelines and scopes
Register pipeline behaviors in order from outermost to innermost. Register behaviors that depend on scoped services with a scoped lifetime and resolve the runtime from the same caller scope. For streams, keep the scope open throughout enumeration.
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");dotnet run --project Samples/CqrsPipelineDemo -c ReleaseCQRS_PIPELINE_PASS confirms that the handler returned its response and the scope released its dependency. See also the handler registry generator.