Repository navigation
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:

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);
}
}| 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 |
In some cases, you might need the Command to return an object or value. In this case, a Command Function is better suited.
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;
}
}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
};
}
}| 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 |
There are a number of async versions of the interfaces, for when you need to call external resources.
For commands that perform asynchronous operations without context:
public interface ICommandObjectAsync
{
Task ExecuteAsync(CancellationToken cancellationToken = default);
}For async commands that require context:
public interface ICommandObjectAsync<in TContext>
{
new Task ExecuteAsync(TContext context, CancellationToken cancellationToken = default);
}For async command functions that return a value:
public interface ICommandFunctionAsync<out TResult>
{
new Task<TResult> ExecuteAsync(CancellationToken cancellationToken = default);
}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);
}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");
}
}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"
};
}
}| 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> |
Copyright © 2022-2026 Envivo Software
-
Objects
-
Configuring your Model
-
Testing your model
-
Other features