Commands/Write Operation

What is it about?

Commands are CQRS write operations that allow the application to optimize and scale its write operations independently, often through specialized command handlers that enforce business rules and update the write models accordingly.

Creating Commands

frontier dotnet add command [name-of-command]

The command generates two files located at ProjectName/src/ProjectNameApi.Application/NameOfCommand/Commands/NameOfCommand/.

NameOfCommandCommand.cs

using Mediator; // using NameOfProject.Application.Features.NameOfCommand.Interfaces; namespace NameOfProject.Application.Features.NameOfCommand.Commands.NameOfCommand { public record NameOfCommandCommand : IRequest { public string Property1 { get; set; } = string.Empty; public string Property2 { get; set; } = string.Empty; public string Property3 { get; set; } = string.Empty; } public class NameOfCommandCommandHandler : IRequestHandler<NameOfCommandCommand> { // private readonly IAuthenticationService _authenticationService; public NameOfCommandCommandHandler(/*IAuthenticationService authenticationService*/) { // _authenticationService = authenticationService; } public async ValueTask<Unit> Handle(NameOfCommandCommand request, CancellationToken cancellationToken) { Console.WriteLine($"Property1: {request.Property1}"); Console.WriteLine($"Property2: {request.Property2}"); Console.WriteLine($"Property3: {request.Property3}"); return Unit.Value; } } }

NameOfCommandCommandValidator.cs

using FluentValidation; namespace ProjectName.Application.Features.NameOfCommand.Queries.NameOfCommand { public class NameOfCommandQueryValidator : AbstractValidator<NameOfCommandQuery> { public NameOfCommandQueryValidator() { RuleFor(v => v.Property1).Cascade(CascadeMode.Stop) .NotEmpty().WithMessage("Property1 field is required.") .EmailAddress().WithMessage("Invalid email format."); RuleFor(v => v.Property2).Cascade(CascadeMode.Continue) .NotEmpty().WithMessage("Property2 field is required.") .MaximumLength(50).WithMessage("Property2 is over the maximum field length of 50."); RuleFor(v => v.Property3).Cascade(CascadeMode.Stop) .NotEmpty().WithMessage("Property3 field is required."); } } }