Csharpessentials mediator

From senrecep/CSharpEssentials · View interactive version

Csharpessentials mediator is an AI agent skill from the GitHub repository senrecep/CSharpEssentials. Use when adding cross-cutting pipeline behaviors to CQRS handlers. Covers ValidationBehavior (CSharpEssentials.Validation; modes Enforce/LogOnly/Off, failure observers; Result failure or EnhancedValidationException), LoggingBehavior (ILoggableRequest), ExceptionHandlingBehavior (converts exceptions

How to use this skill

Skill file

CSharpEssentials.Mediator

Pipeline behaviors for the Mediator source-generator package (not MediatR). Registered once, each behavior runs for every request that matches its marker interface.

Installation

dotnet add package CSharpEssentials.Mediator
dotnet add package Mediator.SourceGenerator --version 3.0.*   # in the entry project

Namespace

using CSharpEssentials.Mediator;   // ICacheable, ILoggableRequest, ITransactionalRequest, ILockedRequest, IIdempotentRequest, ValidationMode, behaviors
using Microsoft.Extensions.DependencyInjection;   // AddMediatorBehaviors and the other AddMediator* methods

Register behaviors

// Program.cs
builder.Services.AddMediator();           // Mediator source generator
builder.Services.AddMediatorBehaviors();  // all 5 behaviors: validation, logging, exception handling, caching, transaction scope

// Or selectively
builder.Services.AddMediatorValidationBehavior();
builder.Services.AddMediatorLoggingBehavior();
builder.Services.AddMediatorExceptionHandlingBehavior();
builder.Services.AddMediatorCachingBehavior();
builder.Services.AddMediatorTransactionBehavior();

Register ValidationBehavior first: invalid requests should never reach the handler. Selective registration runs behaviors in registration order. For Native AOT use options.PipelineBehaviors = MediatorExtensions.DefaultPipelineBehaviors in AddMediator(...) and services.AddMediatorValidationOptions() instead of the open-generic registrations.


ValidationBehavior (CSharpEssentials.Validation)

Runs the registered validators before the handler. On failure the handler does not run, and the errors come back by return type:

| TResponse | Failure result |

|-------------|---------------|

| Result | Result.Failure(errors) returned directly |

| Result<T> | Result<T>.Failure(errors) returned directly |

| Any other type | EnhancedValidationException thrown, caught by GlobalExceptionHandler (400 ProblemDetails) |

public class CreateOrderValidator : Validator<CreateOrderCommand>
{
    protected override ValueTask Configure(CreateOrderCommand model, RuleContext<CreateOrderCommand> rules, CancellationToken ct = default)
    {
        rules.For(() => model.UserId).NotEqual(Guid.Empty);
        rules.For(() => model.Amount).GreaterThan(0m);
        return ValueTask.CompletedTask;
    }
}

// using CSharpEssentials.Validation; using CSharpEssentials.Validation.Validators; using CSharpEssentials.Validation.Extensions;
builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly);

Validation modes (ValidationBehaviorOptions.DefaultMode, or per request with IValidationModeOverride): Enforce (default) rejects invalid requests, LogOnly runs the validators and notifies observers but lets the request continue, Off skips validation.

builder.Services.AddMediatorValidationBehavior(options => options.DefaultMode = ValidationMode.LogOnly);

Every IValidationFailureObserver in DI is called on a failure in Enforce and LogOnly mode; the built-in LoggingValidationFailureObserver logs it and increments the cse.mediator.validation.failures counter on the CSharpEssentials.Mediator meter. A validator that throws (other than OperationCanceledException) becomes a Validator.Exception error.


LoggingBehavior (ILoggableRequest)

Interface hierarchy:

// ILoggableRequest: base marker
// IRequestLoggable: logs request body only
// IResponseLoggable: logs response body only
// IRequestResponseLoggable: logs both
public record GetUserQuery(Guid UserId)
    : IQuery<Result<UserDto>>, IRequestResponseLoggable;

public record SendEmailCommand(string To, string Body)
    : ICommand<Result>, IRequestLoggable;  // response has no PII, so log request only

ExceptionHandlingBehavior: automatic for Result-returning handlers

Registered by AddMediatorBehaviors() or AddMediatorExceptionHandlingBehavior() as a singleton pipeline behavior between LoggingBehavior and CachingBehavior. When a handler throws, the behavior converts the exception to Result.Failure(Error.Exception(ex)). OperationCanceledException always propagates.

No marker interface is needed: once the behavior is registered it applies to any handler whose TResponse is Result or Result<T>. Handlers returning other types pass through untouched.

Pipeline execution order

| Position | Behavior | Activation |

|----------|----------|-----------|

| 1 | ValidationBehavior | Every request |

| 2 | LoggingBehavior | ILoggableRequest |

| 3 | ExceptionHandlingBehavior | Result / Result<T> return types |

| 4 | CachingBehavior | ICacheable |

| 5 | TransactionScopeBehavior | ITransactionalRequest |

Error shape

Error.Exception(ex) produces an error with:

// No interface needed. Applies to all handlers returning Result or Result<T> once the behavior is registered
public record ProcessPaymentCommand(Guid OrderId, decimal Amount)
    : ICommand<Result>;

public class ProcessPaymentHandler : ICommandHandler<ProcessPaymentCommand, Result>
{
    private readonly IPaymentClient _paymentGateway;

    public ProcessPaymentHandler(IPaymentClient paymentGateway)
        => _paymentGateway = paymentGateway;

    public async ValueTask<Result> Handle(ProcessPaymentCommand command, CancellationToken ct)
    {
        // If this throws, ExceptionHandlingBehavior converts it to Result.Failure(Error.Exception(ex))
        // instead of letting the exception propagate to the caller.
        await _paymentGateway.ChargeAsync(command.OrderId, command.Amount, ct);
        return Result.Success();
    }
}

// Caller always receives a Result, so no try/catch is needed
Result result = await mediator.Send(new ProcessPaymentCommand(orderId, 99.99m));
if (result.IsFailure)
{
    // result.FirstError.Code        => "HttpRequestException"
    // result.FirstError.Description => "Payment gateway timed out"
}

CachingBehavior (ICacheable)

Requires IDistributedCache registration.

public record GetProductQuery(int ProductId)
    : IQuery<Result<ProductDto>>, ICacheable
{
    public bool BypassCache   => false;   // true: skip the cache entirely (no lookup, no store)
    public bool CacheFailures => false;   // never cache error results
    public string CacheKey    => $"product:{ProductId}";
    public TimeSpan Expiration => TimeSpan.FromMinutes(5);   // zero or negative: no expiration
}

// Requires an IDistributedCache backend (in-memory here; a distributed one in production)
builder.Services.AddDistributedMemoryCache();

TransactionScopeBehavior (ITransactionalRequest)

Wraps the handler in a TransactionScope created with TransactionScopeAsyncFlowOption.Enabled (default isolation level). The scope completes only when the handler returns a successful Result / Result<T> (or a response that is not a Result); a failed Result or an exception rolls it back.

public record PlaceOrderCommand(OrderDto Order)
    : ICommand<Result<Guid>>, ITransactionalRequest;
// No members to implement on ITransactionalRequest

To run the handler through your own data access transaction instead (for example EF Core), register TransactionBehavior and an ITransactionRunner (namespace CSharpEssentials.Transactions). It replaces TransactionScopeBehavior in the pipeline and commits under the same rule:

services.AddMediatorBehaviors();
services.AddMediatorTransactionRunnerBehavior();
services.AddEfCoreTransactionRunner<AppDbContext>(); // CSharpEssentials.EntityFrameworkCore

LockBehavior (ILockedRequest)

Runs one handler at a time per key. The in-process default serializes within one process only; register a distributed IResourceLock for several instances.

public record CapturePaymentCommand(Guid OrderId) : ICommand<Result>, ILockedRequest
{
    public string LockKey => $"order:{OrderId}";
    public TimeSpan? LockTimeout => TimeSpan.FromSeconds(5); // optional; null waits until cancelled
}

services.AddMediatorBehaviors();
services.AddMediatorLockBehavior(); // call after the other behaviors; LockPlacement.OutsideTransaction by default

On a lock timeout a Result handler gets a failed result (Error.Exception(TimeoutException)), because LockBehavior runs inside ExceptionHandlingBehavior. Use LockPlacement.InsideTransaction only with transaction-scoped locks such as pg_advisory_xact_lock.

IdempotencyBehavior (IIdempotentRequest)

Runs a request at most once per key and caller, and replays the stored Result to a retry. Opt-in per request; the work runs through IIdempotencyExecutor from CSharpEssentials.Idempotency.

using CSharpEssentials.Idempotency;   // IdempotencyScope, IdempotencyScopes, IdempotencyExecutionOptions

public record RefundPaymentCommand(string IdempotencyKey, Guid OrderId) : ICommand<Result<Guid>>, IIdempotentRequest;
// optional members: IdempotencyScope (built only with IdempotencyScope.User/Tenant/Client/UserAndTenant/Custom/Global),
// IdempotencyFingerprint (default: SHA-256 of the request JSON), IdempotencyRetention, IdempotencyLease

services.AddMediatorBehaviors();
services.AddIdempotency();   // ASP.NET Core: gives the behavior the request user (IIdempotencyScopeAccessor)
services.AddMediatorIdempotencyBehavior(o => o.ForRequest<RefundPaymentCommand>(p => p.Profile = "payments"));
services.AddIdempotencyExecutor(o => o.AddProfile("payments", p => p.Retention = TimeSpan.FromDays(7)));

Best practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.