TaskHub.Shared

Overview

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.

Package

TaskHub.Shared.Commands.Abstractions

Namespace

TaskHub.Shared.Commands.Abstractions.Behavior

Definition

public interface IPreBehavior<TCommand, TResult>
    where TCommand : ICommand
    where TResult : Result
{
    Task<TResult> HandleAsync(TCommand command, Func<TCommand, CancellationToken, Task<TResult>> next, CancellationToken ct);
}

Usage Example

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>();
    }
}

Registration

Pre-behaviors can be registered in the DI container.

builder.Services.AddScoped<IPreBehavior<TCommand, Result>, IsExistBehavior<TCommand, Result>>();