Class PollyMiddleware
- Namespace
- WorkflowForge.Extensions.Resilience.Polly
- Assembly
- WorkflowForge.Extensions.Resilience.Polly.dll
Middleware that applies Polly resilience policies to workflow operations. Provides enterprise-grade fault tolerance with circuit breakers, retries, and timeouts.
public sealed class PollyMiddleware : IWorkflowOperationMiddleware
- Inheritance
-
PollyMiddleware
- Implements
- Inherited Members
Properties
Name
Gets the name of the middleware.
public string Name { get; }
Property Value
Methods
ExecuteAsync(IWorkflowOperation, IWorkflowFoundry, object?, Func<CancellationToken, Task<object?>>, CancellationToken)
Executes the operation middleware logic.
public Task<object?> ExecuteAsync(IWorkflowOperation operation, IWorkflowFoundry foundry, object? inputData, Func<CancellationToken, Task<object?>> next, CancellationToken cancellationToken = default)
Parameters
operationIWorkflowOperationThe operation being executed.
foundryIWorkflowFoundryThe foundry context providing properties, logger, and services.
inputDataobjectInput data passed to the operation.
nextFunc<CancellationToken, Task<object>>Delegate to invoke the next middleware in the pipeline or the operation itself. Call this to continue the operation execution. Not calling this will short-circuit the operation.
cancellationTokenCancellationTokenCancellation token for the operation execution.
Returns
- Task<object>
A task representing the operation execution result. The result can be null or any object depending on the operation.
Remarks
Middleware should:
- Call
next(cancellationToken) to continue operation execution - Handle exceptions appropriately (log, transform, or rethrow)
- Clean up resources in finally blocks
- Respect cancellation tokens
- Preserve operation results unless intentionally transforming them
Example implementation:
public async Task<object?> ExecuteAsync(
IWorkflowOperation operation,
IWorkflowFoundry foundry,
object? inputData,
Func<CancellationToken, Task<object?>> next,
CancellationToken cancellationToken)
{
// Pre-execution logic
Logger.LogInformation("Starting operation: {Name}", operation.Name);
try
{
// Execute operation
var result = await next(cancellationToken).ConfigureAwait(false);
// Post-execution logic (success)
Logger.LogInformation("Operation completed: {Name}", operation.Name);
return result;
}
catch (Exception ex)
{
// Post-execution logic (failure)
Logger.LogError(ex, "Operation failed: {Name}", operation.Name);
throw;
}
}
Exceptions
- OperationCanceledException
Thrown when the operation execution is cancelled.
FromOptions(PollyMiddlewareOptions, IWorkflowForgeLogger)
Creates middleware whose pipeline is composed from the supplied options. Only the strategies whose settings are enabled are added, in the order timeout, retry, circuit breaker.
public static PollyMiddleware FromOptions(PollyMiddlewareOptions options, IWorkflowForgeLogger logger)
Parameters
optionsPollyMiddlewareOptionsThe options describing the pipeline.
loggerIWorkflowForgeLoggerThe logger to use.
Returns
- PollyMiddleware
A new Polly middleware instance.
Exceptions
- ArgumentNullException
Thrown when options or logger is null.
WithCircuitBreakerPolicy(IWorkflowForgeLogger, int, TimeSpan?, string?)
Creates middleware with a circuit breaker policy.
public static PollyMiddleware WithCircuitBreakerPolicy(IWorkflowForgeLogger logger, int failureThreshold = 5, TimeSpan? durationOfBreak = null, string? name = null)
Parameters
loggerIWorkflowForgeLoggerThe logger to use.
failureThresholdintNumber of failures before opening the circuit.
durationOfBreakTimeSpan?Duration to keep the circuit open.
namestringOptional name for the middleware.
Returns
- PollyMiddleware
A new Polly middleware instance.
WithComprehensivePolicy(IWorkflowForgeLogger, int, TimeSpan?, int, TimeSpan?, TimeSpan?, string?)
Creates comprehensive middleware combining retry, circuit breaker, and timeout policies.
public static PollyMiddleware WithComprehensivePolicy(IWorkflowForgeLogger logger, int maxRetryAttempts = 3, TimeSpan? baseDelay = null, int circuitBreakerThreshold = 5, TimeSpan? circuitBreakerDuration = null, TimeSpan? timeoutDuration = null, string? name = null)
Parameters
loggerIWorkflowForgeLoggerThe logger to use.
maxRetryAttemptsintMaximum number of retry attempts.
baseDelayTimeSpan?Base delay for exponential backoff.
circuitBreakerThresholdintCircuit breaker failure threshold.
circuitBreakerDurationTimeSpan?Circuit breaker open duration.
timeoutDurationTimeSpan?Operation timeout duration.
namestringOptional name for the middleware.
Returns
- PollyMiddleware
A new comprehensive Polly middleware instance.
WithRetryPolicy(IWorkflowForgeLogger, int, TimeSpan?, TimeSpan?, string?)
Creates middleware with a retry policy using exponential backoff.
public static PollyMiddleware WithRetryPolicy(IWorkflowForgeLogger logger, int maxRetryAttempts = 3, TimeSpan? baseDelay = null, TimeSpan? maxDelay = null, string? name = null)
Parameters
loggerIWorkflowForgeLoggerThe logger to use.
maxRetryAttemptsintMaximum number of retry attempts.
baseDelayTimeSpan?Base delay for exponential backoff.
maxDelayTimeSpan?Maximum delay between retries.
namestringOptional name for the middleware.
Returns
- PollyMiddleware
A new Polly middleware instance.
WithTimeoutPolicy(IWorkflowForgeLogger, TimeSpan, string?)
Creates middleware with a timeout policy.
public static PollyMiddleware WithTimeoutPolicy(IWorkflowForgeLogger logger, TimeSpan timeout, string? name = null)
Parameters
loggerIWorkflowForgeLoggerThe logger to use.
timeoutTimeSpanThe timeout duration.
namestringOptional name for the middleware.
Returns
- PollyMiddleware
A new Polly middleware instance.