IPreBehavior defines a pre-processing step in the command execution pipeline.
It is invoked before the main command handler to perform validation, existence checks, authorization, or other domain preconditions.
A pre-handler can optionally short-circuit the pipeline by returning a result early.
TaskHub.Shared.Commands.Abstractions
TaskHub.Shared.Commands.Abstractions.Behavior
public interface IPreBehavior<TCommand, TResult>
where TCommand : ICommand
where TResult : Result
{
Task<TResult> HandleAsync(TCommand command, Func<TCommand, CancellationToken, Task<TResult>> next, CancellationToken ct);
}
public class IsExistBehavior<TCommand, TResult>(IReadRepository rep) : IPreBehavior<TCommand, TResult>
where TCommand : IJobCommand
where TResult : Result
{
public async Task<TResult> HandleAsync(TCommand cmd, Func<TCommand, CancellationToken, Task<TResult>> next, CancellationToken ct)
{
if (await rep.IsExistAsync(cmd.JobId, ct))
{
return await next(cmd, ct);
}
return ResultFactory.ItemNotFound.As<TResult>();
}
}
Pre-behaviors can be registered in the DI container.
builder.Services.AddScoped<IPreBehavior<TCommand, Result>, IsExistBehavior<TCommand, Result>>();