Table of Contents

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

string

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

operation IWorkflowOperation

The operation being executed.

foundry IWorkflowFoundry

The foundry context providing properties, logger, and services.

inputData object

Input data passed to the operation.

next Func<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.

cancellationToken CancellationToken

Cancellation 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

options PollyMiddlewareOptions

The options describing the pipeline.

logger IWorkflowForgeLogger

The 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

logger IWorkflowForgeLogger

The logger to use.

failureThreshold int

Number of failures before opening the circuit.

durationOfBreak TimeSpan?

Duration to keep the circuit open.

name string

Optional 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

logger IWorkflowForgeLogger

The logger to use.

maxRetryAttempts int

Maximum number of retry attempts.

baseDelay TimeSpan?

Base delay for exponential backoff.

circuitBreakerThreshold int

Circuit breaker failure threshold.

circuitBreakerDuration TimeSpan?

Circuit breaker open duration.

timeoutDuration TimeSpan?

Operation timeout duration.

name string

Optional 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

logger IWorkflowForgeLogger

The logger to use.

maxRetryAttempts int

Maximum number of retry attempts.

baseDelay TimeSpan?

Base delay for exponential backoff.

maxDelay TimeSpan?

Maximum delay between retries.

name string

Optional 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

logger IWorkflowForgeLogger

The logger to use.

timeout TimeSpan

The timeout duration.

name string

Optional name for the middleware.

Returns

PollyMiddleware

A new Polly middleware instance.