PollyExtensions.HybridCache 1.0.0

dotnet add package PollyExtensions.HybridCache --version 1.0.0
                    
NuGet\Install-Package PollyExtensions.HybridCache -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PollyExtensions.HybridCache" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="PollyExtensions.HybridCache" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="PollyExtensions.HybridCache" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add PollyExtensions.HybridCache --version 1.0.0
                    
#r "nuget: PollyExtensions.HybridCache, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package PollyExtensions.HybridCache@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=PollyExtensions.HybridCache&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=PollyExtensions.HybridCache&version=1.0.0
                    
Install as a Cake Tool

PollyExtensions.HybridCache

NuGet NuGet Downloads Build Status License

A community extension for Polly that provides HybridCache-based caching strategies for typed resilience pipelines.

📦 Installation

dotnet add package PollyExtensions.HybridCache

🚀 Quick Start

using Microsoft.Extensions.DependencyInjection;
using Polly;
using PollyExtensions.HybridCache;

// 1. Setup HybridCache (requires .NET 9+)
var services = new ServiceCollection();
services.AddHybridCache();
var provider = services.BuildServiceProvider();

var cache = provider.GetRequiredService<HybridCache>();

// 2. Configure caching strategy
var options = new HybridCacheStrategyOptions<string>
{
    Cache = cache,
    Ttl = TimeSpan.FromMinutes(5),
    CacheKeyGenerator = ctx => ctx.OperationKey ?? "default-key"
};

// 3. Build a resilience pipeline with caching
var pipeline = new ResiliencePipelineBuilder<string>()
    .AddHybridCache(options)
    .Build();

// 4. Execute operations - first call caches, second retrieves
var result1 = await pipeline.ExecuteAsync(async _ => 
{
    // Expensive operation
    await Task.Delay(1000);
    return "expensive-result";
});

var result2 = await pipeline.ExecuteAsync(async _ => 
{
    // This won't execute - returns cached value
    await Task.Delay(1000);
    return "expensive-result";
});

Console.WriteLine(result1); // "expensive-result" (cached)
Console.WriteLine(result2); // "expensive-result" (from cache, instant!)

✨ Features

  • Type-Safe: Works with typed resilience pipelines (ResiliencePipelineBuilder<TResult>)
  • HybridCache Integration: Leverages Microsoft's modern caching library
  • Flexible Key Generation: Custom key generators or use OperationKey
  • Configurable TTL: Control time-to-live and sliding expiration
  • 100% Test Coverage: Thoroughly tested and production-ready

📖 Usage Examples

Complex Types

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var options = new HybridCacheStrategyOptions<User>
{
    Cache = cache,
    Ttl = TimeSpan.FromMinutes(10),
    CacheKeyGenerator = ctx => $"user:{ctx.Properties["userId"]}"
};

var pipeline = new ResiliencePipelineBuilder<User>()
    .AddHybridCache(options)
    .Build();

var user = await pipeline.ExecuteAsync(async ctx =>
{
    var userId = (int)ctx.Properties["userId"];
    return await FetchUserFromDatabase(userId);
}, 
new ResilienceContext { Properties = { ["userId"] = 123 } });

Sliding Expiration

var options = new HybridCacheStrategyOptions<string>
{
    Cache = cache,
    Ttl = TimeSpan.FromMinutes(5),
    UseSlidingExpiration = true // Reset TTL on each access
};

Combining with Other Strategies

var pipeline = new ResiliencePipelineBuilder<string>()
    .AddRetry(new RetryStrategyOptions<string>
    {
        MaxRetryAttempts = 3
    })
    .AddHybridCache(options) // Cache successful results
    .AddTimeout(TimeSpan.FromSeconds(30))
    .Build();

⚙️ Configuration

HybridCacheStrategyOptions<TResult>

Property Type Default Description
Cache HybridCache (required) The HybridCache instance
Ttl TimeSpan 5 minutes Time-to-live for cached entries
UseSlidingExpiration bool false Enable sliding expiration
CacheKeyGenerator Func<ResilienceContext, string?> ctx => ctx.OperationKey Custom key generator

🔒 Type Safety

This package only supports typed pipelines (ResiliencePipelineBuilder<TResult>). Untyped pipelines (object) are not supported to ensure type safety and avoid serialization issues.

// ✅ SUPPORTED
var typedPipeline = new ResiliencePipelineBuilder<string>()
    .AddHybridCache(options)
    .Build();

// ❌ NOT SUPPORTED
var untypedPipeline = new ResiliencePipelineBuilder()
    .AddHybridCache(options) // Compile error - no extension method
    .Build();

📋 Requirements

  • .NET 9.0 or later
  • Polly.Core 8.0+
  • Microsoft.Extensions.Caching.Hybrid 9.3.0+

🤝 Contributing

Contributions are welcome! Please:

  1. Fork the repo
  2. Create a feature branch
  3. Add tests for new features
  4. Ensure all tests pass
  5. Submit a PR

📜 License

This project is licensed under the BSD-3-Clause License - same as Polly.

🙏 Acknowledgments


Note: This is a community-maintained package and not an official part of Polly.Core.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 295 11/21/2025

See CHANGELOG.md for details