Class PreconditionAttribute
- Namespace
- Signal.Application.Commands.Preconditions
- Assembly
- Signal.Application.dll
A check executed before a command runs (and before its arguments are bound). Apply it to a command method, an ICommand class, or a CommandModule class (then it applies to all its commands). Derive from it to build custom preconditions; resolve services through Services.
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class PreconditionAttribute : Attribute
- Inheritance
-
PreconditionAttribute
- Derived
- Inherited Members
Examples
public sealed class RequireWorkingHoursAttribute : PreconditionAttribute
{
public override ValueTask<PreconditionResult> CheckAsync(CommandContext context, CancellationToken ct) =>
ValueTask.FromResult(DateTime.Now.Hour is >= 8 and < 18 ? PreconditionResult.Success : Fail("Office hours only."));
}
Properties
ErrorMessage
Overrides the default failure message. Set to an empty string to fail silently.
public string? ErrorMessage { get; set; }
Property Value
Order
Execution order; lower values run first. Stateful checks such as cooldowns should run last.
public virtual int Order { get; }
Property Value
Methods
CheckAsync(CommandContext, CancellationToken)
Checks whether the command may run.
public abstract ValueTask<PreconditionResult> CheckAsync(CommandContext context, CancellationToken cancellationToken)
Parameters
contextCommandContextThe command context.
cancellationTokenCancellationTokenCancelled when the host shuts down.
Returns
- ValueTask<PreconditionResult>
The check result.
Fail(CommandContext, string, params object?[])
Creates a failure with a localised default message (see TextKey), honoring ErrorMessage. Translations are looked up in the culture of the command's conversation.
protected PreconditionResult Fail(CommandContext context, string textKey, params object?[] args)
Parameters
contextCommandContextThe command context.
textKeystringThe text key.
argsobject[]Format arguments of the text.
Returns
- PreconditionResult
The failed result.
Fail(string)
Creates a failure honoring ErrorMessage.
protected PreconditionResult Fail(string defaultMessage)
Parameters
defaultMessagestringThe message used when ErrorMessage is not set.
Returns
- PreconditionResult
The failed result.