Skip to content

command objects

vijay@envivo edited this page Jul 25, 2026 · 7 revisions

Command Objects

Sometimes, you need Methods whose parameter selections are dependent on another parameter.

An example might involve two object parameters, where the selection of the first parameter affects the available objects in the second parameter.

This is where a Command Object would be used. Instead of using a Method that has Parameters, we use a Command Object that has Properties (where each property represents the original parameter). Here is an example:

public class CommandSampleWithObjects : ICommandObject  //👈
{
    public Guid Id { get; init; }

	/// <remarks>
	/// You cannot add, remove, or clear this set
	/// </remarks>
    [AllowedOperations(canAdd: false, canRemove: false, canClear: false)]
    public ICollection<BasicObject> AllAvailableObjects { get; } = [];

    /// <summary>
    /// Items selected from this set are not available in Set B
    /// </summary>
	/// <remarks>
	/// You cannot add items to this set, but you can modify them
	/// </remarks>
    [FilterQuerySpecification(typeof(SetA_QuerySpecification))]
    [UI(UiRenderOption.InlineSimple, preferredControl: UiControlType.Select)]
    [AllowedOperations(canAdd: false, canModify: true)]
    public BasicObject SelectionA { get; set; }

    /// <summary>
    /// Items selected from this set are not available in Set A
    /// </summary>
    [FilterQuerySpecification(typeof(SetB_QuerySpecification))]
    [UI(UiRenderOption.InlineSimple, preferredControl: UiControlType.Select)]
    [AllowedOperations(canAdd: false, canModify: true)]
    public BasicObject SelectionB { get; set; }

    /// <summary>
    /// Executes the command when SelectionA and SelectionB have values
    /// </summary>
    [Visible(false)]
    public bool IsReadyToExecute => (SelectionA != null && SelectionB != null);

    public void Execute() //👈
    {
        // TODO: Perform some logic using the 'parameters' (i.e. the properties on this object)
    }
}

Whenever this object is created in the mode, it is rendered as an interactive dialog:


Command arguments

ICommandObject

Sometimes you need to pass additional context or arguments to your command when it executes. The generic version of ICommandObject allows you to inject a context parameter that will be available during execution.

public class UserUpdateCommand : ICommandObject<UserUpdateContext> //👈
{
    public string UserName { get; set; }

    public string NewEmail { get; set; }

    public void Execute(UserUpdateContext context) //👈
    {
        // Access the given context
        var userId = context.UserId;
        var transactionId = context.TransactionId;
        
        // Perform the update with both command properties and context
        _userService.UpdateEmail(userId, UserName, NewEmail, transactionId);
    }
}

When to use

Interface Use when...
ICommandObject The command has all the data it needs in its own properties
ICommandObject<TContext> You need to inject external data (service references, transaction IDs, user info, etc.) at execution time

Command Functions

In some cases, you might need the Command to return an object or value. In this case, a Command Function is better suited.

Example: Command Function without Context

public class GenerateReportCommand : ICommandFunction<Report> //👈
{
    [UI(UiRenderOption.InlineSimple, preferredControl: UiControlType.DateRange)]
    public DateRange ReportPeriod { get; set; }

    [UI(UiRenderOption.InlineSimple)]
    public ReportType ReportType { get; set; }

    public Report Execute() //👈 no arguments needed
    {
        var report = new Report
        {
            Title = $"{ReportType} - {ReportPeriod.Start} to {ReportPeriod.End}",
            Data = _reportService.GenerateData(ReportType, ReportPeriod),
            GeneratedAt = DateTime.Now
        };
        return report;
    }
}

Example: Command Function with Context

public class CalculateTaxCommand : ICommandFunction<TaxCalculationContext, TaxResult> //👈
{
    public decimal Amount { get; set; }

    [UI(UiRenderOption.InlineSimple)]
    public TaxBracket Bracket { get; set; }

    public TaxResult Execute(TaxCalculationContext context) //👈 argument provided
    {
        var baseTax = Amount * Bracket.Rate;
        var adjustments = context.ApplyAdjustments(baseTax);
        
        return new TaxResult
        {
            BaseTax = baseTax,
            AdjustedTax = adjustments,
            TransactionId = context.TransactionId
        };
    }
}

When to use Command Functions

Interface Use when...
ICommandObject You only need to perform an action with side effects
ICommandFunction<TResult> You need to return a computed value based on command properties
ICommandFunction<TContext, TResult> You need both injected context AND to return a computed result

Async versions

There are a number of async versions of the interfaces, for when you need to call external resources.

ICommandObjectAsync

For commands that perform asynchronous operations without context:

public interface ICommandObjectAsync
{
    Task ExecuteAsync(CancellationToken cancellationToken = default);
}

ICommandObjectAsync

For async commands that require context:

public interface ICommandObjectAsync<in TContext>
{
    new Task ExecuteAsync(TContext context, CancellationToken cancellationToken = default);
}

ICommandFunctionAsync

For async command functions that return a value:

public interface ICommandFunctionAsync<out TResult>
{
    new Task<TResult> ExecuteAsync(CancellationToken cancellationToken = default);
}

ICommandFunctionAsync<TContext, TResult>

For async command functions with context that return a value:

public interface ICommandFunctionAsync<in TContext, out TResult> 
    : ICommandFunction<TContext, TResult>
{
    new Task<TResult> ExecuteAsync(TContext context, CancellationToken cancellationToken = default);
}

Example: Async Command Object

public class EmailDocumentCommand : ICommandObjectAsync //👈
{
    public string DocumentContent { get; set; }

    public string Subject { get; set; }

    public string Recipients { get; set; }

    public async Task ExecuteAsync(CancellationToken cancellationToken = default) //👈
    {
        // Validate
        if (string.IsNullOrWhiteSpace(DocumentContent))
            throw new ValidationException("Content cannot be empty");

        if (string.IsNullOrWhiteSpace(Subject))
            throw new ValidationException("Subject cannot be empty");

        if (string.IsNullOrWhiteSpace(Recipients))
            throw new ValidationException("Recipients cannot be empty");

        // Async email operation
        await _emailService.EmailAsync(Recipients, Subject, DocumentContent, cancellationToken);

        // Async audit logging
        await _auditService.LogAsync($"Notification '{Subject}' sent");
    }
}

Example: Async Command Function

public class ProcessOrderCommand : ICommandFunctionAsync<OrderContext, OrderConfirmation> //👈
{
    [UI(preferredControl: UiControlType.Currency)]
    public decimal TotalAmount { get; set; }

    public bool ApplyLoyaltyDiscount { get; set; }

    public async Task<OrderConfirmation> ExecuteAsync(OrderContext context, CancellationToken ct = default) //👈
    {
        var finalAmount = ApplyLoyaltyDiscount ? TotalAmount * 0.9m : TotalAmount;
        
        var (paymentResult, inventoryResult) = await Task.WhenAll(
            _paymentService.ChargeAsync(context.CustomerId, finalAmount, ct),
            _inventoryService.ReserveAsync(context.Items, ct)
        );
        return new OrderConfirmation
        {
            OrderId = Guid.NewGuid(),
            TransactionId = paymentResult.TransactionId,
            FinalAmount = finalAmount,
            Status = inventoryResult.AllAvailable ? "Confirmed" : "Backordered"
        };
    }
}

Choosing the Right Interface

Use Case Recommended Interface
Simple fire-and-forget action ICommandObject
Action with injected context ICommandObject<TContext>
Action that returns a value ICommandFunction<TResult>
Action with context returning value ICommandFunction<TContext, TResult>
Async action ICommandObjectAsync
Async action with context ICommandObjectAsync<TContext>
Async action returning value ICommandFunctionAsync<TResult>
Async action with context returning value ICommandFunctionAsync<TContext, TResult>

Clone this wiki locally