Getting started

To use Polly, you must provide a callback and execute it using a resilience pipeline. A resilience pipeline is a combination of one or more resilience strategies such as retry, timeout, and rate limiter. Polly uses builders to integrate these strategies into a pipeline.

To get started, first add the Polly.Core package to your project by running the following command:

dotnet add package Polly.Core

You can create a ResiliencePipeline using the ResiliencePipelineBuilder class as shown below:

// Create an instance of builder that exposes various extensions for adding resilience strategies
ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions()) // Add retry using the default options
    .AddTimeout(TimeSpan.FromSeconds(10)) // Add 10 seconds timeout
    .Build(); // Builds the resilience pipeline

// Execute the pipeline asynchronously
await pipeline.ExecuteAsync(static async token => { /* Your custom logic goes here */ }, cancellationToken);
Note

Asynchronous methods in the Polly API return ValueTask or ValueTask<T> instead of Task or Task<T>. If you are using Polly in Visual Basic or F#, please read Use with F# and Visual Basic for more information.

Dependency injection

If you prefer to define resilience pipelines using IServiceCollection, you'll need to install the Polly.Extensions package:

dotnet add package Polly.Extensions

then you can define your resilience pipeline using the AddResiliencePipeline(...) extension method as shown:

var services = new ServiceCollection();

// Define a resilience pipeline with the name "my-pipeline"
services.AddResiliencePipeline("my-pipeline", builder =>
{
    builder
        .AddRetry(new RetryStrategyOptions())
        .AddTimeout(TimeSpan.FromSeconds(10));
});

// Build the service provider
var serviceProvider = services.BuildServiceProvider();

// Retrieve a ResiliencePipelineProvider that dynamically creates and caches the resilience pipelines
var pipelineProvider = serviceProvider.GetRequiredService<ResiliencePipelineProvider<string>>();

// Retrieve your resilience pipeline using the name it was registered with
ResiliencePipeline pipeline = pipelineProvider.GetPipeline("my-pipeline");

// Alternatively, you can use keyed services to retrieve the resilience pipeline
pipeline = serviceProvider.GetRequiredKeyedService<ResiliencePipeline>("my-pipeline");

// Execute the pipeline
await pipeline.ExecuteAsync(static async token =>
{
    // Your custom logic goes here
});
Note

You don't need to call the Build method on the builder parameter inside the AddResiliencePipeline.