### Polly Resilience Pipeline Execution Start Log Example Source: https://www.pollydocs.org/advanced/telemetry.html Example log message format when a resilience pipeline begins executing. This log is useful for tracking the start of pipeline operations. ```log Resilience pipeline executing. Source: '{PipelineName}/{PipelineInstance}', Operation Key: '{OperationKey}' ``` -------------------------------- ### GetOptions(string?) Source: https://www.pollydocs.org/api/Polly.DependencyInjection.AddResiliencePipelineContext-1.html Gets the options identified by name. ```APIDOC ### GetOptions(string? name = null) Gets the options identified by `name`. #### Parameters * `name` string The options name, if any. #### Returns TOptions The options instance. #### Type Parameters * `TOptions` The options type. #### Remarks If `name` is null then the global options are returned. ``` -------------------------------- ### Using ResilienceContext in Polly v8 Source: https://www.pollydocs.org/migration-v8.html Demonstrates how to get, use, and return ResilienceContext instances from the pool. Includes examples of attaching and retrieving custom properties using type-safe keys. ```csharp // Create context ResilienceContext context = ResilienceContextPool.Shared.Get(); // Create context with operation key context = ResilienceContextPool.Shared.Get("my-operation-key"); // Attach custom properties ResiliencePropertyKey propertyKey1 = new(Key1); context.Properties.Set(propertyKey1, "value-1"); ResiliencePropertyKey propertyKey2 = new(Key2); context.Properties.Set(propertyKey2, 100); // Bulk attach context.Properties.SetProperties(new Dictionary { { Key1 , "value-1" }, { Key2 , 100 } }, out var oldProperties); // Retrieve custom properties string value1 = context.Properties.GetValue(propertyKey1, "default"); int value2 = context.Properties.GetValue(propertyKey2, 0); // Return the context to the pool ResilienceContextPool.Shared.Return(context); ``` -------------------------------- ### Example Pipeline with Latency Chaos Source: https://www.pollydocs.org/chaos/latency.html Illustrates the integration of the latency chaos strategy within a more complex resilience pipeline, typically placed last. This example includes retry and timeout strategies before the latency chaos, demonstrating a layered approach to resilience testing. ```csharp var pipeline = new ResiliencePipelineBuilder() .AddRetry(new RetryStrategyOptions { ShouldHandle = new PredicateBuilder().Handle(), BackoffType = DelayBackoffType.Exponential, UseJitter = true, // Adds a random factor to the delay MaxRetryAttempts = 4, Delay = TimeSpan.FromSeconds(3), }) .AddTimeout(TimeSpan.FromSeconds(5)) .AddChaosLatency(new ChaosLatencyStrategyOptions // Chaos strategies are usually placed as the last ones in the pipeline { Latency = TimeSpan.FromSeconds(10), InjectionRate = 0.1 }) .Build(); ``` -------------------------------- ### Add Polly.Extensions Package Source: https://www.pollydocs.org/advanced/telemetry.html Install the Polly.Extensions package to enable telemetry features. ```bash dotnet add package Polly.Extensions ``` -------------------------------- ### Add Polly.Core Package Source: https://www.pollydocs.org/getting-started.html Install the Polly.Core package using the .NET CLI to add resilience capabilities to your project. ```bash dotnet add package Polly.Core ``` -------------------------------- ### ChaosOutcomeStrategyOptions Constructor Source: https://www.pollydocs.org/api/Polly.Simmy.Outcomes.ChaosOutcomeStrategyOptions-1.html Initializes a new instance of the ChaosOutcomeStrategyOptions class. No specific setup is required beyond instantiation. ```csharp public ChaosOutcomeStrategyOptions() ``` -------------------------------- ### RetryStrategyOptions Constructor Source: https://www.pollydocs.org/api/Polly.Retry.RetryStrategyOptions-1.html Initializes a new instance of the RetryStrategyOptions class. No specific setup is required for this constructor. ```csharp public RetryStrategyOptions() ``` -------------------------------- ### V7 Policy Registry Example Source: https://www.pollydocs.org/migration-v8.html Demonstrates creating, adding, and retrieving policies from a V7 `PolicyRegistry`. Note the use of `AddOrUpdate` for modifying existing policies. ```csharp // Create a registry var registry = new PolicyRegistry(); // Add a policy registry.Add(PolicyKey, Policy.Timeout(TimeSpan.FromSeconds(10))); // Try get a policy registry.TryGet(PolicyKey, out IAsyncPolicy? policy); // Try get a generic policy registry.TryGet>(PolicyKey, out IAsyncPolicy? genericPolicy); // Update a policy registry.AddOrUpdate( PolicyKey, Policy.Timeout(TimeSpan.FromSeconds(10)), (key, previous) => Policy.Timeout(TimeSpan.FromSeconds(10))); __ ``` -------------------------------- ### Register and Fetch Resilience Pipelines Source: https://www.pollydocs.org/pipelines/resilience-pipeline-registry.html Demonstrates registering both generic and non-generic pipeline builders using TryAddBuilder. Shows how to fetch pipelines and check for their existence. ```csharp var registry = new ResiliencePipelineRegistry(); // Register builder for pipeline "A" registry.TryAddBuilder("A", (builder, context) => { // Define your pipeline builder.AddRetry(new RetryStrategyOptions()); }); // Register generic builder for pipeline "A"; you can use the same key // because generic and non-generic pipelines are stored separately registry.TryAddBuilder("A", (builder, context) => { // Define your pipeline builder.AddRetry(new RetryStrategyOptions()); }); // Fetch pipeline "A" ResiliencePipeline pipelineA = registry.GetPipeline("A"); // Fetch generic pipeline "A" ResiliencePipeline genericPipelineA = registry.GetPipeline("A"); // Returns false since pipeline "unknown" isn't registered var doesPipelineExist = registry.TryGetPipeline("unknown", out var pipeline); // Throws KeyNotFoundException because pipeline "unknown" isn't registered try { registry.GetPipeline("unknown"); } catch (KeyNotFoundException) { // Handle the exception } ``` -------------------------------- ### Create and Get Resilience Pipelines Source: https://www.pollydocs.org/pipelines/resilience-pipeline-registry.html Demonstrates creating a registry adapter and obtaining resilience pipelines with specified rate limiting configurations. Ensures proper disposal of the registry adapter. ```csharp public static class Program { public static void Main() { using var registryAdapter = new PipelineRegistryAdapter(); registryAdapter.GetOrCreateResiliencePipeline("Pipeline foo", 1, 10, 100, 1000); registryAdapter.GetOrCreateResiliencePipeline("Pipeline bar", 2, 20, 200, 2000); } } public sealed class PipelineRegistryAdapter : IDisposable { private readonly ResiliencePipelineRegistry _resiliencePipelineRegistry = new(); private bool _disposed; public void Dispose() { if (!_disposed) { _resiliencePipelineRegistry.Dispose(); _disposed = true; } } private static PartitionedRateLimiter CreateConcurrencyLimiter(string partitionKey, int permitLimit) => PartitionedRateLimiter.Create(context => RateLimitPartition.GetConcurrencyLimiter( partitionKey: partitionKey, factory: partitionKey => new ConcurrencyLimiterOptions { PermitLimit = permitLimit, QueueLimit = 0 })); private static PartitionedRateLimiter CreateFixedWindowLimiter(string partitionKey, int permitLimit, TimeSpan window) => PartitionedRateLimiter.Create(context => RateLimitPartition.GetFixedWindowLimiter( partitionKey: partitionKey, factory: partitionKey => new FixedWindowRateLimiterOptions { PermitLimit = permitLimit, QueueLimit = 0, Window = window })); public ResiliencePipeline GetOrCreateResiliencePipeline(string partitionKey, int maximumConcurrentThreads, int sendLimitPerSecond, int sendLimitPerHour, int sendLimitPerDay) { return _resiliencePipelineRegistry.GetOrAddPipeline(partitionKey, (builder, context) => { PartitionedRateLimiter? threadLimiter = null; PartitionedRateLimiter? requestLimiter = null; // outer strategy: limit threads builder.AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = args => { threadLimiter = CreateConcurrencyLimiter(partitionKey, maximumConcurrentThreads); return threadLimiter.AcquireAsync(args.Context, permitCount: 1, args.Context.CancellationToken); } }); // inner strategy: limit requests (by second, hour, day) builder.AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = args => { PartitionedRateLimiter[] limiters = [ CreateFixedWindowLimiter(partitionKey, sendLimitPerSecond, TimeSpan.FromSeconds(1)), CreateFixedWindowLimiter(partitionKey, sendLimitPerHour, TimeSpan.FromHours(1)), CreateFixedWindowLimiter(partitionKey, sendLimitPerDay, TimeSpan.FromDays(1)), ]; requestLimiter = PartitionedRateLimiter.CreateChained(limiters); return requestLimiter.AcquireAsync(args.Context, permitCount: 1, args.Context.CancellationToken); } }); // unlike other strategies, rate limiters disposed manually context.OnPipelineDisposed(() => { threadLimiter?.Dispose(); requestLimiter?.Dispose(); }); }); } } ``` -------------------------------- ### Polly Resilience Event Log Example Source: https://www.pollydocs.org/advanced/telemetry.html Example log message format for a general resilience event. This log is recorded whenever a resilience event occurs. ```log Resilience event occurred. EventName: '{EventName}', Source: '{PipelineName}/{PipelineInstance}/{StrategyName}', Operation Key: '{OperationKey}', Result: '{Result}' ``` -------------------------------- ### Initialize ResiliencePipelineBuilder Source: https://www.pollydocs.org/api/Polly.ResiliencePipelineBuilder-1.html Initializes a new instance of the ResiliencePipelineBuilder class. This is the starting point for building a resilience pipeline. ```csharp public ResiliencePipelineBuilder() ``` -------------------------------- ### Polly Execution Attempt Log Example Source: https://www.pollydocs.org/advanced/telemetry.html Example log message format for the completion of an individual execution attempt within a resilience strategy. This log details the attempt number and whether it was handled. ```log Execution attempt. Source: '{PipelineName}/{PipelineInstance}/{StrategyName}', Operation Key: '{OperationKey}', Result: '{Result}', Handled: '{Handled}', Attempt: '{Attempt}', Execution Time: '{ExecutionTime}ms' ``` -------------------------------- ### Build and Test Solution Source: https://www.pollydocs.org/community/git-workflow.html Run tests from the repository root to ensure the solution builds successfully and all tests pass. Check for errors, warnings, and maintain code coverage. ```bash dotnet test ``` -------------------------------- ### Polly Resilience Pipeline Execution End Log Example Source: https://www.pollydocs.org/advanced/telemetry.html Example log message format for when a resilience pipeline finishes execution. This log provides information about the pipeline's outcome and performance. ```log Resilience pipeline executed. Source: '{PipelineName}/{PipelineInstance}', Operation Key: '{OperationKey}', Result: '{Result}', Execution Health: '{ExecutionHealth}', Execution Time: {ExecutionTime}ms ``` -------------------------------- ### V8 Resilience Pipeline Registry Example Source: https://www.pollydocs.org/migration-v8.html Shows how to create a V8 `ResiliencePipelineRegistry`, add builders for pipelines, and retrieve pipelines. Emphasizes the append-only nature and dynamic caching. ```csharp // Create a registry var registry = new ResiliencePipelineRegistry(); // Add a pipeline using a builder, when the pipeline is retrieved it will be dynamically built and cached registry.TryAddBuilder(PipelineKey, (builder, context) => builder.AddTimeout(TimeSpan.FromSeconds(10))); // Try get a pipeline registry.TryGetPipeline(PipelineKey, out ResiliencePipeline? pipeline); // Try get a generic pipeline registry.TryGetPipeline(PipelineKey, out ResiliencePipeline? genericPipeline); // Get or add pipeline registry.GetOrAddPipeline(PipelineKey, builder => builder.AddTimeout(TimeSpan.FromSeconds(10))); __ ``` -------------------------------- ### ChaosBehaviorStrategyOptions Constructor Source: https://www.pollydocs.org/api/Polly.Simmy.Behavior.ChaosBehaviorStrategyOptions.html Initializes a new instance of the ChaosBehaviorStrategyOptions class. No specific setup is required for this default constructor. ```csharp public ChaosBehaviorStrategyOptions() ``` -------------------------------- ### Configure and Use Circuit Breaker Strategy Source: https://www.pollydocs.org/strategies/circuit-breaker.html This example demonstrates how to configure a circuit breaker with specific options for failure ratio, sampling duration, minimum throughput, break duration, and exception handling. It then simulates operations that throw exceptions to show how the circuit breaker behaves, including catching `BrokenCircuitException`. ```csharp var pipeline = new ResiliencePipelineBuilder() .AddCircuitBreaker(new CircuitBreakerStrategyOptions { FailureRatio = 0.1, SamplingDuration = TimeSpan.FromSeconds(1), MinimumThroughput = 3, BreakDuration = TimeSpan.FromSeconds(30), ShouldHandle = new PredicateBuilder().Handle() }) .Build(); for (int i = 0; i < 10; i++) { try { pipeline.Execute(() => throw new SomeExceptionType()); } catch (SomeExceptionType) { Console.WriteLine("Operation failed please try again."); } catch (BrokenCircuitException) { Console.WriteLine("Operation failed too many times please try again later."); } } ``` -------------------------------- ### OnFaultInjectedArguments.Fault Property Source: https://www.pollydocs.org/api/Polly.Simmy.Fault.OnFaultInjectedArguments.html Gets the fault that was injected. ```APIDOC ## Fault ### Description Gets the fault that was injected. ### Property Value Exception ``` -------------------------------- ### ResilienceContextPool.Shared Source: https://www.pollydocs.org/api/Polly.ResilienceContextPool.html Gets the shared instance of the ResilienceContextPool. ```APIDOC ## Property: Shared ### Description Gets the shared pool instance. ### Returns ResilienceContextPool - The shared pool instance. ``` -------------------------------- ### Initialize ResiliencePipelineRegistry with Options Source: https://www.pollydocs.org/api/Polly.Registry.ResiliencePipelineRegistry-1.html Initializes a new instance of the ResiliencePipelineRegistry class with custom options, including a builder factory and comparer. Throws ValidationException or ArgumentNullException if options are invalid or null. ```csharp public ResiliencePipelineRegistry(ResiliencePipelineRegistryOptions options) ``` -------------------------------- ### PipelineExecutedArguments.Duration Property Source: https://www.pollydocs.org/api/Polly.Telemetry.PipelineExecutedArguments.html Gets the duration of the pipeline execution. ```APIDOC ## Duration ### Description Gets the pipeline execution duration. ### Property Value TimeSpan - The pipeline execution duration. ``` -------------------------------- ### OnBehaviorInjectedArguments.Context Property Source: https://www.pollydocs.org/api/Polly.Simmy.Behavior.OnBehaviorInjectedArguments.html Gets the resilience context instance. ```APIDOC ## Context ### Description Gets the resilience context instance. ### Property Value ResilienceContext ``` -------------------------------- ### Initialize ChaosLatencyStrategyOptions Source: https://www.pollydocs.org/api/Polly.Simmy.Latency.ChaosLatencyStrategyOptions.html Initializes a new instance of the ChaosLatencyStrategyOptions class. This is the default constructor. ```csharp public ChaosLatencyStrategyOptions() ``` -------------------------------- ### OnTimeoutArguments Timeout Property Source: https://www.pollydocs.org/api/Polly.Timeout.OnTimeoutArguments.html Gets the timeout value assigned. ```csharp public TimeSpan Timeout { get; } ``` -------------------------------- ### Manage Resource Disposal with Registry Source: https://www.pollydocs.org/pipelines/resilience-pipeline-registry.html Illustrates how the registry manages pipeline resources and how disposing of the registry also disposes of its pipelines. Includes an example of executing a pipeline after the registry has been disposed. ```csharp var registry = new ResiliencePipelineRegistry(); // This instance is valid even after reload. ResiliencePipeline pipeline = registry .GetOrAddPipeline("A", (builder, context) => builder.AddTimeout(TimeSpan.FromSeconds(10))); // Dispose the registry registry.Dispose(); try { pipeline.Execute(() => { }); } catch (ObjectDisposedException) { // Using a pipeline that was disposed by the registry } ``` -------------------------------- ### ResilienceEvent EventName Property Source: https://www.pollydocs.org/api/Polly.Telemetry.ResilienceEvent.html Gets the name of the resilience event. ```csharp public string EventName { get; } ``` -------------------------------- ### F# Example: Using Polly with ValueTask Source: https://www.pollydocs.org/advanced/use-with-fsharp-and-visual-basic.html Demonstrates how to use Polly's ResiliencePipeline in F# with asynchronous operations returning ValueTask. Includes synchronous and asynchronous execution, with and without results. Requires the IcedTasks library for easier ValueTask handling. ```fsharp open FSharp.Control open System open System.Threading open System.Threading.Tasks open IcedTasks open Polly let getBestFilmAsync token = task { do! Task.Delay(1000, token) return "https://www.imdb.com/title/tt0080684/" } let demo () = task { // The ResiliencePipelineBuilder creates a ResiliencePipeline // that can be executed synchronously or asynchronously // and for both void and result-returning user-callbacks. let pipeline = ResiliencePipelineBuilder() .AddTimeout(TimeSpan.FromSeconds(5)) .Build() let token = CancellationToken.None // Synchronously pipeline.Execute(fun () -> printfn "Hello, world!") // Asynchronously // Note that Polly expects a ValueTask to be returned, so the function uses the valueTask builder // from IcedTasks to make it easier to use ValueTask. See https://github.com/TheAngryByrd/IcedTasks. do! pipeline.ExecuteAsync( fun token -> valueTask { printfn "Hello, world! Waiting for 2 seconds..." do! Task.Delay(1000, token) printfn "Wait complete." } , token ) // Synchronously with result let someResult = pipeline.Execute(fun token -> "some-result") // Asynchronously with result // Note that Polly expects a ValueTask to be returned, so the function uses the valueTask builder // from IcedTasks to make it easier to use ValueTask. See https://github.com/TheAngryByrd/IcedTasks. let! bestFilm = pipeline.ExecuteAsync( fun token -> valueTask { let! url = getBestFilmAsync(token) return url } , token ) printfn $"Link to the best film: {bestFilm}" } ``` -------------------------------- ### SeverityProviderArguments Event Property Source: https://www.pollydocs.org/api/Polly.Telemetry.SeverityProviderArguments.html Gets the resilience event that occurred. ```csharp public ResilienceEvent Event { get; } ``` -------------------------------- ### Create and Execute Resilience Pipeline Source: https://www.pollydocs.org/pipelines/index.html Demonstrates creating a resilience pipeline with a concurrency limiter and executing various types of callbacks, including asynchronous void, synchronous void, and callbacks returning values. Also shows how to execute callbacks with custom state and context properties. ```csharp // Creating a new resilience pipeline ResiliencePipeline pipeline = new ResiliencePipelineBuilder() .AddConcurrencyLimiter(100) .Build(); // Executing an asynchronous void callback await pipeline.ExecuteAsync( async token => await MyMethodAsync(token), cancellationToken); // Executing a synchronous void callback pipeline.Execute(() => MyMethod()); // Executing an asynchronous callback that returns a value await pipeline.ExecuteAsync( async token => await httpClient.GetAsync(endpoint, token), cancellationToken); // Executing an asynchronous callback without allocating a lambda await pipeline.ExecuteAsync( static async (state, token) => await state.httpClient.GetAsync(state.endpoint, token), (httpClient, endpoint), // State provided here cancellationToken); // Executing an asynchronous callback and passing custom data // 1. Retrieve a context from the shared pool ResilienceContext context = ResilienceContextPool.Shared.Get(cancellationToken); // 2. Add custom data to the context context.Properties.Set(new ResiliencePropertyKey("my-custom-data"), "my-custom-data"); // 3. Execute the callback await pipeline.ExecuteAsync(static async context => { // Retrieve custom data from the context var customData = context.Properties.GetValue( new ResiliencePropertyKey("my-custom-data"), "default-value"); Console.WriteLine("Custom Data: {0}", customData); await MyMethodAsync(context.CancellationToken); }, context); // 4. Optionally, return the context to the shared pool ResilienceContextPool.Shared.Return(context); ``` -------------------------------- ### ResiliencePropertyKey.Key Property Source: https://www.pollydocs.org/api/Polly.ResiliencePropertyKey-1.html Gets the name of the resilience property key. ```csharp public string Key { get; } ``` -------------------------------- ### Initialize RateLimiterStrategyOptions Source: https://www.pollydocs.org/api/Polly.RateLimiting.RateLimiterStrategyOptions.html Initializes a new instance of the RateLimiterStrategyOptions class. This is the default constructor. ```csharp public RateLimiterStrategyOptions() ``` -------------------------------- ### HedgingActionGeneratorArguments.AttemptNumber Property Source: https://www.pollydocs.org/api/Polly.Hedging.HedgingActionGeneratorArguments-1.html Gets the zero-based hedging attempt number. ```csharp public int AttemptNumber { get; } ``` -------------------------------- ### Initialize ChaosFaultStrategyOptions Source: https://www.pollydocs.org/api/Polly.Simmy.Fault.ChaosFaultStrategyOptions.html Initializes a new instance of the ChaosFaultStrategyOptions class. This is the default constructor. ```csharp public ChaosFaultStrategyOptions()__ ``` -------------------------------- ### TimeoutStrategyOptions.Timeout Property Source: https://www.pollydocs.org/api/Polly.Timeout.TimeoutStrategyOptions.html Gets or sets the default timeout duration for the strategy. ```APIDOC ## TimeoutStrategyOptions.Timeout ### Description Gets or sets the default timeout duration for the resilience strategy. ### Property Value TimeSpan - The default timeout. Must be between 10 milliseconds and 24 hours. Defaults to 30 seconds. ### Remarks This property defines the standard timeout period. If a `TimeoutGenerator` is not provided, this value will be used. ``` -------------------------------- ### Configure Upstream Remote Source: https://www.pollydocs.org/community/git-workflow.html Configure the upstream remote to point to the main Polly repository. This is a one-time setup after cloning your fork. ```git git remote add upstream https://github.com/App-vNext/Polly.git ``` -------------------------------- ### ResilienceEvent Severity Property Source: https://www.pollydocs.org/api/Polly.Telemetry.ResilienceEvent.html Gets the severity level of the resilience event. ```csharp public ResilienceEventSeverity Severity { get; } ``` -------------------------------- ### Initialize ResiliencePipelineRegistry Source: https://www.pollydocs.org/api/Polly.Registry.ResiliencePipelineRegistry-1.html Initializes a new instance of the ResiliencePipelineRegistry class with the default comparer. ```csharp public ResiliencePipelineRegistry() ``` -------------------------------- ### Add Polly.Extensions Package Source: https://www.pollydocs.org/getting-started.html Install the Polly.Extensions package using the .NET CLI to enable Polly integration with ASP.NET Core's dependency injection. ```bash dotnet add package Polly.Extensions ``` -------------------------------- ### SeverityProviderArguments Source Property Source: https://www.pollydocs.org/api/Polly.Telemetry.SeverityProviderArguments.html Gets the source that produced the resilience event. ```csharp public ResilienceTelemetrySource Source { get; } ``` -------------------------------- ### Initialize FallbackStrategyOptions Source: https://www.pollydocs.org/api/Polly.Fallback.FallbackStrategyOptions-1.html Initializes a new instance of the FallbackStrategyOptions class. This is the default constructor. ```csharp public FallbackStrategyOptions() ``` -------------------------------- ### ChaosOutcomeStrategyOptions.OnOutcomeInjected Source: https://www.pollydocs.org/api/Polly.Simmy.Outcomes.ChaosOutcomeStrategyOptions-1.html Gets or sets the delegate that's invoked when the outcome is injected. ```APIDOC ## ChaosOutcomeStrategyOptions.OnOutcomeInjected ### Description Gets or sets the delegate that's invoked when the outcome is injected. ### Property Value Func, ValueTask> Defaults to null. ### Request Example ```csharp options.OnOutcomeInjected = async (args) => { /* handle outcome injection */ }; ``` ### Response N/A ``` -------------------------------- ### OnLatencyInjectedArguments Latency Property Source: https://www.pollydocs.org/api/Polly.Simmy.Latency.OnLatencyInjectedArguments.html Gets the TimeSpan representing the latency that was injected. ```csharp public TimeSpan Latency { get; } ``` -------------------------------- ### Create Chained Sliding Window Rate Limiters Source: https://www.pollydocs.org/strategies/rate-limiter.html Demonstrates creating a rate limiter that combines two sliding window limiters with different configurations, partitioned by a user ID. This allows for applying multiple rate limits, such as requests per minute and requests per second, to individual users. ```csharp // Use the user's ID as the partition key. var partitionKey = "user-id"; var firstSlidingWindow = PartitionedRateLimiter.Create((context) => { return RateLimitPartition.GetSlidingWindowLimiter(partitionKey, (partitionKey) => new() { PermitLimit = 100, Window = TimeSpan.FromMinutes(1), }); }); var secondSlidingWindow = PartitionedRateLimiter.Create((context) => { return RateLimitPartition.GetSlidingWindowLimiter(partitionKey, (partitionKey) => new() { PermitLimit = 10, Window = TimeSpan.FromSeconds(1), }); }); // Create a rate limiter that combines the two sliding windows. var chainedRateLimiter = PartitionedRateLimiter.CreateChained(firstSlidingWindow, secondSlidingWindow); // Create the pipeline using the rate limiter that chains the windows together. new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = (context) => chainedRateLimiter.AcquireAsync(context.Context), }) .Build(); ``` -------------------------------- ### OnFaultInjectedArguments Fault Property Source: https://www.pollydocs.org/api/Polly.Simmy.Fault.OnFaultInjectedArguments.html Gets the exception representing the fault that was injected. ```csharp public Exception Fault { get; } ``` -------------------------------- ### Rate Limit Policies in Polly v8 Source: https://www.pollydocs.org/migration-v8.html Shows how to configure a sliding window rate limiter using `ResiliencePipelineBuilder` in Polly v8. Ensure the `Polly.RateLimiting` package is added. ```csharp // The equivalent to Polly v7's RateLimit is the SlidingWindowRateLimiter. // // Polly exposes just a simple wrapper to the APIs exposed by the System.Threading.RateLimiting APIs. // There is no need to create separate instances for sync and async flows as ResiliencePipeline handles both scenarios. ResiliencePipeline pipeline = new ResiliencePipelineBuilder() .AddRateLimiter(new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions { PermitLimit = 100, SegmentsPerWindow = 4, Window = TimeSpan.FromMinutes(1), })) .Build(); // The creation of generic pipeline is almost identical. // // Polly exposes the same set of rate-limiter extensions for both ResiliencePipeline and ResiliencePipeline. ResiliencePipeline pipelineT = new ResiliencePipelineBuilder() .AddRateLimiter(new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions { PermitLimit = 100, SegmentsPerWindow = 4, Window = TimeSpan.FromMinutes(1), })) .Build(); ``` -------------------------------- ### RetryDelay Property Source: https://www.pollydocs.org/api/Polly.Retry.OnRetryArguments-1.html Gets the calculated delay before the next retry attempt. ```csharp public TimeSpan RetryDelay { get; } ``` -------------------------------- ### Configure ResiliencePipelineRegistryOptions Source: https://www.pollydocs.org/pipelines/resilience-pipeline-registry.html Demonstrates how to configure options for ResiliencePipelineRegistry, including custom comparers, builder factory, and name formatters. Useful for advanced customization when using complex registry keys. ```csharp var options = new ResiliencePipelineRegistryOptions { BuilderComparer = StringComparer.OrdinalIgnoreCase, PipelineComparer = StringComparer.OrdinalIgnoreCase, BuilderFactory = () => new ResiliencePipelineBuilder { InstanceName = "lets change the default of InstanceName", Name = "lets change the default of Name", }, BuilderNameFormatter = key => $"key:{key}", InstanceNameFormatter = key => $"instance-key:{key}", }; var registry = new ResiliencePipelineRegistry(); ``` -------------------------------- ### StateProvider Property Source: https://www.pollydocs.org/api/Polly.CircuitBreaker.CircuitBreakerStrategyOptions-1.html Gets or sets the state provider for the circuit breaker. ```APIDOC ## StateProvider ### Description Gets or sets the state provider for the circuit breaker. ### Property `CircuitBreakerStateProvider? StateProvider { get; set; }` ### Property Value `CircuitBreakerStateProvider` ### Remarks The default value is null. ``` -------------------------------- ### Context Creation and Usage in Polly V7 Source: https://www.pollydocs.org/migration-v8.html Illustrates the creation and usage of `Polly.Context` in Polly V7, including setting operation keys and attaching/retrieving custom properties. ```csharp // Create context Context context = new Context(); // Create context with operation key context = new Context("my-operation-key"); // Attach custom properties context[Key1] = "value-1"; context[Key2] = 100; // Retrieve custom properties string value1 = (string)context[Key1]; int value2 = (int)context[Key2]; // Bulk attach context = new Context("my-operation-key", new Dictionary { { Key1 , "value-1" }, { Key2 , 100 } }); ``` -------------------------------- ### ResiliencePipelineRegistry() Constructor Source: https://www.pollydocs.org/api/Polly.Registry.ResiliencePipelineRegistry-1.html Initializes a new instance of the ResiliencePipelineRegistry class with the default comparer. ```APIDOC ## ResiliencePipelineRegistry() ### Description Initializes a new instance of the ResiliencePipelineRegistry class with the default comparer. ### Method ResiliencePipelineRegistry() ### Parameters None ### Returns ResiliencePipelineRegistry ``` -------------------------------- ### HedgingActionGeneratorArguments.Callback Property Source: https://www.pollydocs.org/api/Polly.Hedging.HedgingActionGeneratorArguments-1.html Gets the callback function passed to the hedging strategy. ```csharp public Func>> Callback { get; } ``` -------------------------------- ### OnCircuitHalfOpenedArguments.Context Property Source: https://www.pollydocs.org/api/Polly.CircuitBreaker.OnCircuitHalfOpenedArguments.html Gets the context associated with the execution of a user-provided callback. ```APIDOC ## Context ### Description Gets the context associated with the execution of a user-provided callback. ### Property Value ResilienceContext ``` -------------------------------- ### Visual Basic Resilience Pipeline Example Source: https://www.pollydocs.org/advanced/use-with-fsharp-and-visual-basic.html Demonstrates creating and executing a ResiliencePipeline in Visual Basic for synchronous and asynchronous operations, including those returning results. Note the use of ValueTask and AsTask() for asynchronous operations in VB.NET. ```vb Imports System.Threading Imports Polly Module Program Sub Main() Demo().Wait() End Sub Async Function Demo() As Task ' The ResiliencePipelineBuilder creates a ResiliencePipeline ' that can be executed synchronously or asynchronously ' and for both void and result-returning user-callbacks. Dim pipeline = New ResiliencePipelineBuilder().AddTimeout(TimeSpan.FromSeconds(5)).Build() ' Synchronously pipeline.Execute(Sub() Console.WriteLine("Hello, world!") End Sub) ' Asynchronously ' Note that the function is wrapped in a ValueTask for Polly to use as VB.NET cannot ' await ValueTask directly, and AsTask() is used to convert the ValueTask returned by ' ExecuteAsync() to a Task so it can be awaited. Await pipeline.ExecuteAsync(Function(token) Return New ValueTask(GreetAndWaitAsync(token)) End Function, CancellationToken.None).AsTask() ' Synchronously with result Dim someResult = pipeline.Execute(Function(token) Return "some-result" End Function) ' Asynchronously with result ' Note that the function is wrapped in a ValueTask(Of String) for Polly to use as VB.NET cannot ' await ValueTask directly, and AsTask() is used to convert the ValueTask(Of String) returned by ' ExecuteAsync() to a Task(Of String) so it can be awaited. Dim bestFilm = Await pipeline.ExecuteAsync(Function(token) Return New ValueTask(Of String)(GetBestFilmAsync(token)) End Function, CancellationToken.None).AsTask() Console.WriteLine("Link to the best film: {0}", bestFilm) End Function Async Function GreetAndWaitAsync(token As CancellationToken) As Task Console.WriteLine("Hello, world! Waiting for 1 second...") Await Task.Delay(1000, token) End Function Async Function GetBestFilmAsync(token As CancellationToken) As Task(Of String) Await Task.Delay(1000, token) Return "https://www.imdb.com/title/tt0080684/" End Function End Module ``` -------------------------------- ### TimeoutStrategyOptions.TimeoutGenerator Property Source: https://www.pollydocs.org/api/Polly.Timeout.TimeoutStrategyOptions.html Gets or sets a delegate that generates the timeout duration for each execution. ```APIDOC ## TimeoutStrategyOptions.TimeoutGenerator ### Description Gets or sets a timeout generator that dynamically generates the timeout duration for a given execution. ### Property Value Func>? - The delegate for generating timeouts. Defaults to null. ### Remarks If this generator returns a `TimeSpan` less than or equal to `TimeSpan.Zero`, the timeout strategy will not take effect for that execution. Returning `TimeSpan.InfiniteTimeSpan` effectively disables the timeout for that specific execution. ``` -------------------------------- ### Rate Limit Policies in Polly v7 Source: https://www.pollydocs.org/migration-v8.html Demonstrates the creation of synchronous and asynchronous rate limit policies, including generic versions, in Polly v7. ```csharp // Create sync rate limiter ISyncPolicy syncPolicy = Policy.RateLimit( numberOfExecutions: 100, perTimeSpan: TimeSpan.FromMinutes(1))); // Create async rate limiter IAsyncPolicy asyncPolicy = Policy.RateLimitAsync( numberOfExecutions: 100, perTimeSpan: TimeSpan.FromMinutes(1))); // Create generic sync rate limiter ISyncPolicy syncPolicyT = Policy.RateLimit( numberOfExecutions: 100, perTimeSpan: TimeSpan.FromMinutes(1))); // Create generic async rate limiter IAsyncPolicy asyncPolicyT = Policy.RateLimitAsync( numberOfExecutions: 100, perTimeSpan: TimeSpan.FromMinutes(1))); ``` -------------------------------- ### TimeoutStrategyOptions.OnTimeout Property Source: https://www.pollydocs.org/api/Polly.Timeout.TimeoutStrategyOptions.html Gets or sets the delegate that is invoked when a timeout occurs during execution. ```APIDOC ## TimeoutStrategyOptions.OnTimeout ### Description Gets or sets the timeout delegate that raised when timeout occurs. ### Property Value Func? - The delegate to invoke on timeout. Defaults to null. ### Remarks This property allows you to specify custom logic to execute when the timeout is triggered. The `OnTimeoutArguments` provide context about the timeout event. ``` -------------------------------- ### Hedging Strategy with Event Subscription Source: https://www.pollydocs.org/strategies/hedging.html Sets up a hedging strategy that subscribes to the OnHedging event, allowing custom actions to be performed before a hedged action is executed. ```csharp // Subscribe to hedging events. var optionsOnHedging = new HedgingStrategyOptions { OnHedging = static args => { Console.WriteLine($"OnHedging: Attempt number {args.AttemptNumber}"); return default; } }; // Add a hedging strategy with a HedgingStrategyOptions instance to the pipeline new ResiliencePipelineBuilder().AddHedging(optionsOnHedging); ``` -------------------------------- ### Initialize HedgingStrategyOptions Source: https://www.pollydocs.org/api/Polly.Hedging.HedgingStrategyOptions-1.html Initializes a new instance of the HedgingStrategyOptions class. This is the default constructor. ```csharp public HedgingStrategyOptions() ``` -------------------------------- ### EnrichmentContext TelemetryEvent Property Source: https://www.pollydocs.org/api/Polly.Telemetry.EnrichmentContext-2.html Gets the info about the telemetry event. ```csharp public TelemetryEventArguments TelemetryEvent { get; } ``` -------------------------------- ### ChaosOutcomeStrategyOptions.OutcomeGenerator Source: https://www.pollydocs.org/api/Polly.Simmy.Outcomes.ChaosOutcomeStrategyOptions-1.html Gets or sets the generator that generates the outcomes to be injected. This property is required. ```APIDOC ## ChaosOutcomeStrategyOptions.OutcomeGenerator ### Description Gets or sets the generator that generates the outcomes to be injected. ### Property Value Func?>> Defaults to null. This property is required. ### Request Example ```csharp options.OutcomeGenerator = async (args) => await ValueTask.FromResult(Outcome.ForFailure(new Exception("Injected failure"))); ``` ### Response N/A ``` -------------------------------- ### Bulkhead Policies in Polly v7 Source: https://www.pollydocs.org/migration-v8.html Illustrates the creation of synchronous and asynchronous bulkhead policies, including generic versions, in Polly v7. ```csharp // Create sync bulkhead ISyncPolicy syncPolicy = Policy.Bulkhead( maxParallelization: 100, maxQueuingActions: 50); // Create async bulkhead IAsyncPolicy asyncPolicy = Policy.BulkheadAsync( maxParallelization: 100, maxQueuingActions: 50); // Create generic sync bulkhead ISyncPolicy syncPolicyT = Policy.Bulkhead( maxParallelization: 100, maxQueuingActions: 50); // Create generic async bulkhead IAsyncPolicy asyncPolicyT = Policy.BulkheadAsync( maxParallelization: 100, maxQueuingActions: 50); ``` -------------------------------- ### TimeProvider Property Source: https://www.pollydocs.org/api/Polly.StrategyBuilderContext.html Gets the TimeProvider used by the resilience strategy within the StrategyBuilderContext. ```csharp public TimeProvider TimeProvider { get; } ``` -------------------------------- ### Configure Telemetry with ResiliencePipelineBuilder Source: https://www.pollydocs.org/advanced/telemetry.html Enable telemetry by configuring TelemetryOptions and using the ConfigureTelemetry extension method on ResiliencePipelineBuilder. ```csharp var telemetryOptions = new TelemetryOptions { // Configure logging LoggerFactory = LoggerFactory.Create(builder => builder.AddConsole()) }; // Configure enrichers telemetryOptions.MeteringEnrichers.Add(new MyMeteringEnricher()); // Configure telemetry listeners telemetryOptions.TelemetryListeners.Add(new MyTelemetryListener()); var pipeline = new ResiliencePipelineBuilder() .AddTimeout(TimeSpan.FromSeconds(1)) .ConfigureTelemetry(telemetryOptions) // This method enables telemetry in the builder .Build(); ``` -------------------------------- ### ChaosFaultStrategyOptions.OnFaultInjected Property Source: https://www.pollydocs.org/api/Polly.Simmy.Fault.ChaosFaultStrategyOptions.html Gets or sets the delegate that's raised when the fault is injected. ```APIDOC ## ChaosFaultStrategyOptions.OnFaultInjected Property ### Description Gets or sets the delegate that's raised when the fault is injected. ### Property Type Func? ### Default Value null ### Code ```csharp public Func? OnFaultInjected { get; set; } ``` ``` -------------------------------- ### RetryStrategyOptions.BackoffType Source: https://www.pollydocs.org/api/Polly.Retry.RetryStrategyOptions-1.html Gets or sets the type of the back-off. This property is ignored when DelayGenerator is set. ```APIDOC ## BackoffType ### Description Gets or sets the type of the back-off. ### Property Value DelayBackoffType ### Remarks This property is ignored when DelayGenerator is set. ### Code ```csharp public DelayBackoffType BackoffType { get; set; } ``` ``` -------------------------------- ### Configure Latency Chaos Strategy Options Source: https://www.pollydocs.org/chaos/latency.html Demonstrates various ways to configure ChaosLatencyStrategyOptions, including default settings, basic options with fixed latency and injection rate, dynamic latency generation using a custom function, and options for receiving notifications when latency is injected. Use these configurations to tailor the latency chaos behavior to specific testing needs. ```csharp var optionsDefault = new ChaosLatencyStrategyOptions(); ``` ```csharp var basicOptions = new ChaosLatencyStrategyOptions { Latency = TimeSpan.FromSeconds(30), InjectionRate = 0.1 }; ``` ```csharp var optionsWithLatencyGenerator = new ChaosLatencyStrategyOptions { LatencyGenerator = static args => { TimeSpan latency = args.Context.OperationKey switch { "DataLayer" => TimeSpan.FromMilliseconds(500), "ApplicationLayer" => TimeSpan.FromSeconds(2), _ => TimeSpan.Zero }; return new ValueTask(latency); }, InjectionRate = 0.1 }; ``` ```csharp var optionsOnLatencyInjected = new ChaosLatencyStrategyOptions { Latency = TimeSpan.FromSeconds(30), InjectionRate = 0.1, OnLatencyInjected = static args => { Console.WriteLine($"OnLatencyInjected, Latency: {args.Latency}, Operation: {args.Context.OperationKey}."); return default; } }; ``` -------------------------------- ### ChaosBehaviorStrategyOptions.OnBehaviorInjected Property Source: https://www.pollydocs.org/api/Polly.Simmy.Behavior.ChaosBehaviorStrategyOptions.html Gets or sets the delegate that's raised when the behavior is injected. ```APIDOC ## ChaosBehaviorStrategyOptions.OnBehaviorInjected ### Description Gets or sets the delegate that's raised when the behavior is injected. ### Property Value Func? ### Details Defaults to null. ### Example ```csharp options.OnBehaviorInjected = async (args) => { // Log or perform actions when behavior is injected await ValueTask.CompletedTask; }; ``` ``` -------------------------------- ### ChaosFaultStrategyOptions Constructor Source: https://www.pollydocs.org/api/Polly.Simmy.Fault.ChaosFaultStrategyOptions.html Initializes a new instance of the ChaosFaultStrategyOptions class. ```APIDOC ## ChaosFaultStrategyOptions() ### Description Initializes a new instance of the ChaosFaultStrategyOptions class. ### Method Constructor ### Code ```csharp public ChaosFaultStrategyOptions() ``` ``` -------------------------------- ### Duration Property Source: https://www.pollydocs.org/api/Polly.Retry.OnRetryArguments-1.html Gets the duration of the current attempt that led to this retry event. ```csharp public TimeSpan Duration { get; } ``` -------------------------------- ### ResiliencePropertyKey.Key Property Source: https://www.pollydocs.org/api/Polly.ResiliencePropertyKey-1.html Gets the name of the resilience property key. ```APIDOC ## Key Property ### Description Gets the name of the key. ### Property Value (string) - The name of the key. ``` -------------------------------- ### Bulkhead Policies (Concurrency Limiter) in Polly v8 Source: https://www.pollydocs.org/migration-v8.html Demonstrates configuring a concurrency limiter using `ResiliencePipelineBuilder` in Polly v8. Ensure the `Polly.RateLimiting` package is added. ```csharp // Create pipeline with concurrency limiter. Because ResiliencePipeline supports both sync and async // callbacks, there is no need to define it twice. ResiliencePipeline pipeline = new ResiliencePipelineBuilder() .AddConcurrencyLimiter(permitLimit: 100, queueLimit: 50) .Build(); // Create a generic pipeline with concurrency limiter. Because ResiliencePipeline supports both sync and async // callbacks, there is no need to define it twice. ResiliencePipeline pipelineT = new ResiliencePipelineBuilder() .AddConcurrencyLimiter(permitLimit: 100, queueLimit: 50) .Build(); ``` -------------------------------- ### Add Polly.Testing Package Source: https://www.pollydocs.org/advanced/testing.html Add the Polly.Testing package to your test project using the dotnet CLI. ```bash dotnet add package Polly.Testing ``` -------------------------------- ### HedgingActionGeneratorArguments.PrimaryContext Property Source: https://www.pollydocs.org/api/Polly.Hedging.HedgingActionGeneratorArguments-1.html Gets the primary resilience context as received by the hedging strategy. ```csharp public ResilienceContext PrimaryContext { get; } ``` -------------------------------- ### FallbackStrategyOptions.OnFallback Property Source: https://www.pollydocs.org/api/Polly.Fallback.FallbackStrategyOptions-1.html Gets or sets the event delegate that is raised when fallback happens. ```APIDOC ## OnFallback Property ### Description Gets or sets event delegate that is raised when fallback happens. ### Property Value Func, ValueTask> ``` -------------------------------- ### ResiliencePipelineRegistry(ResiliencePipelineRegistryOptions) Constructor Source: https://www.pollydocs.org/api/Polly.Registry.ResiliencePipelineRegistry-1.html Initializes a new instance of the ResiliencePipelineRegistry class with a custom builder factory and comparer. ```APIDOC ## ResiliencePipelineRegistry(ResiliencePipelineRegistryOptions options) ### Description Initializes a new instance of the ResiliencePipelineRegistry class with a custom builder factory and comparer. ### Method ResiliencePipelineRegistry(ResiliencePipelineRegistryOptions options) ### Parameters #### Parameters - **options** (ResiliencePipelineRegistryOptions) - Required - The registry options. ### Returns ResiliencePipelineRegistry ### Exceptions - **ValidationException** - Thrown when `options` are invalid. - **ArgumentNullException** - Thrown when `options` are null. ``` -------------------------------- ### Create Partitioned Concurrency Rate Limiter Source: https://www.pollydocs.org/strategies/rate-limiter.html Illustrates retrieving a partition key from ResilienceContext and creating a partitioned concurrency limiter. Use this when you need to apply rate limits based on specific keys extracted from the execution context. ```csharp var partitionedLimiter = PartitionedRateLimiter.Create(context => { // Extract the partition key. string partitionKey = GetPartitionKey(context); return RateLimitPartition.GetConcurrencyLimiter( partitionKey, key => new ConcurrencyLimiterOptions { PermitLimit = 100 }); }); new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { // Provide a custom rate limiter delegate. RateLimiter = args => { return partitionedLimiter.AcquireAsync(args.Context, 1, args.Context.CancellationToken); } }); ``` -------------------------------- ### HedgingPredicateArguments AttemptNumber Property Source: https://www.pollydocs.org/api/Polly.Hedging.HedgingPredicateArguments-1.html Gets the zero-based attempt number for the resilience operation. ```csharp public int? AttemptNumber { get; } ``` -------------------------------- ### TryAddBuilder Source: https://www.pollydocs.org/api/Polly.Registry.ResiliencePipelineRegistry-1.html Tries to add a resilience pipeline builder to the registry, useful for on-demand pipeline creation. ```APIDOC ## TryAddBuilder(TKey key, Action> configure) ### Description Tries to add a resilience pipeline builder to the registry. ### Method Signature ```csharp public bool TryAddBuilder(TKey key, Action> configure) ``` ### Parameters #### Path Parameters - **key** (TKey) - Required - The key used to identify the pipeline builder. - **configure** (Action>) - Required - The action that configures the resilience pipeline builder. ### Returns - **bool** - true if the builder was added successfully, false otherwise. ### Remarks Use this method when you want to create the pipeline on-demand when it's first accessed. ### Exceptions - **ArgumentNullException** - Thrown when `configure` is null. - **ObjectDisposedException** - Thrown when the registry is already disposed. ``` ```APIDOC ## TryAddBuilder(TKey key, Action, ConfigureBuilderContext> configure) ### Description Tries to add a generic resilience pipeline builder to the registry. ### Method Signature ```csharp public bool TryAddBuilder(TKey key, Action, ConfigureBuilderContext> configure) ``` ### Parameters #### Path Parameters - **key** (TKey) - Required - The key used to identify the pipeline builder. - **configure** (Action, ConfigureBuilderContext>) - Required - The action that configures the resilience pipeline builder. ### Returns - **bool** - true if the builder was added successfully, false otherwise. ### Type Parameters - **TResult** - The type of result that the resilience pipeline handles. ### Remarks Use this method when you want to create the pipeline on-demand when it's first accessed. ### Exceptions - **ArgumentNullException** - Thrown when `configure` is null. - **ObjectDisposedException** - Thrown when the registry is already disposed. ``` -------------------------------- ### PipelineKey Property Source: https://www.pollydocs.org/api/Polly.DependencyInjection.AddResiliencePipelineContext-1.html Gets the key used to identify the resilience pipeline being created. ```csharp public TKey PipelineKey { get; } ``` -------------------------------- ### Usage of Timing Strategy Extension Source: https://www.pollydocs.org/extensibility/proactive-strategy.html Demonstrates how to use the custom AddTiming extension method to configure and build a resilience pipeline with a timing strategy. ```csharp // Add the proactive strategy to the builder var pipeline = new ResiliencePipelineBuilder() // This is custom extension defined in this sample .AddTiming(new TimingStrategyOptions { Threshold = TimeSpan.FromSeconds(1), OnThresholdExceeded = args => { Console.WriteLine("Execution threshold exceeded!"); return default; }, }) .Build(); ``` -------------------------------- ### OnCircuitOpenedArguments BreakDuration Property Source: https://www.pollydocs.org/api/Polly.CircuitBreaker.OnCircuitOpenedArguments-1.html Gets the duration for which the circuit breaker will remain open. ```csharp public TimeSpan BreakDuration { get; } ``` -------------------------------- ### Configure Resilience Pipelines with Dependency Injection Source: https://www.pollydocs.org/pipelines/index.html Shows how to configure resilience pipelines using `AddResiliencePipeline` extension method for `IServiceCollection` and how to retrieve them later using `ResiliencePipelineProvider`. ```csharp public static void ConfigureMyPipelines(IServiceCollection services) { services.AddResiliencePipeline("pipeline-A", builder => builder.AddConcurrencyLimiter(100)); services.AddResiliencePipeline("pipeline-B", builder => builder.AddRetry(new())); // Later, resolve the pipeline by name using ResiliencePipelineProvider or ResiliencePipelineRegistry var pipelineProvider = services.BuildServiceProvider().GetRequiredService>(); pipelineProvider.GetPipeline("pipeline-A").Execute(() => { }); } ``` -------------------------------- ### ResilienceStrategyDescriptor StrategyInstance Property Source: https://www.pollydocs.org/api/Polly.Testing.ResilienceStrategyDescriptor.html Gets the actual instance of the resilience strategy. This property is read-only. ```csharp public object StrategyInstance { get; } ```