Chd.Caching 10.0.6

dotnet add package Chd.Caching --version 10.0.6
                    
NuGet\Install-Package Chd.Caching -Version 10.0.6
                    
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="Chd.Caching" Version="10.0.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Chd.Caching" Version="10.0.6" />
                    
Directory.Packages.props
<PackageReference Include="Chd.Caching" />
                    
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 Chd.Caching --version 10.0.6
                    
#r "nuget: Chd.Caching, 10.0.6"
                    
#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 Chd.Caching@10.0.6
                    
#: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=Chd.Caching&version=10.0.6
                    
Install as a Cake Addin
#tool nuget:?package=Chd.Caching&version=10.0.6
                    
Install as a Cake Tool

Chd.Caching

NuGet Downloads License: MIT

Chd.Caching is a distributed caching library for .NET 10. It is part of the CHD (Cleverly Handle Difficulty) package family. Mark a method with [Cache] and the result is stored in Redis; the next call with the same arguments returns the cached value until the TTL expires. Cache keys, serialization, and expiration are handled for you.

What Does It Do?

  • Attribute-based caching: Add [Cache(60)] to a method to cache its return value for 60 seconds.
  • Cache invalidation with [UnCache]: Delete a cache entry when a method finishes. Pair it with [Cache] by using the same explicit key so updates and deletes do not leave stale data.
  • Redis backend: Uses StackExchange.Redis.
  • Compile-time weaving: MethodBoundaryAspect.Fody injects the cache logic at build time.
  • Sync and async: Works with ordinary return types and Task<T>.
  • Automatic keys: When you do not pass a key, the cache key is built from the declaring type, method name, and JSON-serialized arguments.
  • Type preservation: The runtime type is stored next to the value so the result deserializes back to the original type.
  • Per-method expiration: TTL is set in seconds on each [Cache] attribute.

Who Is It For?

  • API and service developers who want to reduce repeated database or computation work
  • Applications that share cached data across instances through Redis
  • Test and console projects that need the same caching attributes, initialized with UseRedis(null)

Table of Contents


Stop Writing Cache Logic!

Most projects end up with the same get-or-set cache block on every method. Chd.Caching replaces that with one attribute.

The Problem

// Manual caching, repeated for every method:
public async Task<Product> GetProductAsync(int id)
{
    var cacheKey = $"product_{id}";
    var cached = await _cache.GetStringAsync(cacheKey);

    if (!string.IsNullOrEmpty(cached))
    {
        return JsonSerializer.Deserialize<Product>(cached);
    }

    var product = await _db.Products.FindAsync(id);

    if (product != null)
    {
        var serialized = JsonSerializer.Serialize(product);
        await _cache.SetStringAsync(cacheKey, serialized,
            new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
            });
    }

    return product;
}

The Solution

[Cache(60)] // Cache for 60 seconds
public async Task<Product> GetProductAsync(int id)
{
    return await _db.Products.FindAsync(id);
}

Chd.Caching then:

  • Generates a cache key from the method and its arguments (or uses an explicit key you pass)
  • Serializes and deserializes the result, including its runtime type
  • Applies the TTL you specified
  • Supports both synchronous methods and async Task<T>

Why Chd.Caching?

Concern Without Chd.Caching With Chd.Caching
Boilerplate Get, deserialize, set, and expiration options on every method One attribute: [Cache(60)]
Cache keys Manual strings such as $"product_{id}" Auto-generated from type, method, and arguments
Serialization Manual JSON serialize/deserialize Automatic, with the runtime type stored alongside the value
Expiration Repeated DistributedCacheEntryOptions setup A single constructor argument, in seconds
Async Extra handling for Task<T> Works with Task<T> and synchronous methods
Interception Runtime proxies or hand-written wrappers Compile-time weaving; no proxy and no virtual-method requirement

Installation

Requirements: .NET 10 (net10.0) and a Redis server.

Step 1: Install Package

dotnet add package Chd.Caching --version 10.0.5

NuGet Package Manager:

Install-Package Chd.Caching -Version 10.0.5

Package Reference (.csproj):

<PackageReference Include="Chd.Caching" Version="10.0.5" />

That is the only package you need to add. Chd.Caching brings the Fody weaver and applies [Cache] and [UnCache] at build time automatically.

If the project already has a FodyWeavers.xml file, add <MethodBoundaryAspect /> to it so [Cache] runs with your other weavers:

<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
  <MethodBoundaryAspect />
</Weavers>

Upgrading from earlier versions

Earlier versions of this package asked you to install Fody and MethodBoundaryAspect.Fody yourself and to create a FodyWeavers.xml file. That setup keeps working: you can upgrade this package and leave those references in place.

You may optionally remove the manual Fody and MethodBoundaryAspect.Fody package references; weaving is included in this package. If you keep a FodyWeavers.xml file, it must contain <MethodBoundaryAspect />.


Quick Start Guide

Step 1: Setup Redis with Docker

docker run -d --name redis-cache -p 6379:6379 redis:latest

With a password:

docker run -d --name redis-cache -p 6379:6379 redis:latest redis-server --requirepass my_secret_password

The source repository includes Chd.Caching/Redis/docker-compose.yaml, which publishes Redis on host port 3031 and allows an empty password. If you use that file, set Url to localhost:3031 and omit Password.


Step 2: Configure Chd.Caching

Add configuration to appsettings.json:

{
  "Redis": {
    "Url": "localhost:6379",
    "Password": "my_secret_password"
  }
}

Url must include the host, for example localhost:6379. A value such as :6379 is not valid. Password is optional; omit it if the server does not require authentication.

ASP.NET Core: call UseRedis() after the application is built. The method reads appsettings.json from the current working directory (it does not use the host IConfiguration):

// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseRedis();

app.MapControllers();
app.Run();

Tests and console apps: there is no IApplicationBuilder. Pass null; UseRedis still reads appsettings.json from the current directory:

static CachingTests()
{
    CachingDependenyInjectionExtensions.UseRedis(null);
}

Step 3: Add Cache Attribute

using Chd.Caching;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly AppDbContext _db;

    public ProductsController(AppDbContext db) => _db = db;

    [Cache(60)]
    [HttpGet("{id}")]
    public async Task<Product> GetProduct(int id)
    {
        // Runs once per unique id every 60 seconds
        return await _db.Products
            .Include(p => p.Category)
            .FirstOrDefaultAsync(p => p.Id == id);
    }

    [Cache(30)]
    [HttpGet]
    public async Task<List<Product>> GetProducts()
    {
        return await _db.Products.ToListAsync();
    }

    [Cache(120)]
    [HttpGet("search")]
    public async Task<List<Product>> Search(string query, int page, int pageSize)
    {
        // Unique cache key per query, page, and pageSize
        return await _db.Products
            .Where(p => p.Name.Contains(query))
            .Skip(page * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }
}

For GET /api/products/5:

  1. First call: the method runs and the result is stored for 60 seconds.
  2. Calls within 60 seconds with the same arguments return the cached value.
  3. After 60 seconds the entry expires and the method runs again.

null results are not stored, so a method that returns null runs on every call.


Configuration Reference

Redis Configuration

{
  "Redis": {
    "Url": "localhost:6379",
    "Password": "optional_password"
  }
}
Property Required Description
Url Yes Redis endpoint as host:port, for example localhost:6379. The host must not be omitted.
Password No Redis password. If this value is present, UseRedis builds the connection string {Url},abortConnect=false,password={Password}. If it is omitted, Url is used as the connection string as-is, so you may put a full StackExchange.Redis connection string in Url.

Do not set the password in both places. If Password is set, put only host:port in Url.


Cache Attribute

[Cache(seconds)]
[Cache(seconds, key)]
  • seconds: Absolute expiration in seconds.
  • key (optional): A literal cache key. It is not a template: {id} is not replaced with the argument value. Every call to the method shares that one key. If key is omitted, a unique key is generated from the declaring type, method name, and arguments.
[Cache(60)]    // 1 minute, automatic key
[Cache(300)]   // 5 minutes
[Cache(3600)]  // 1 hour
[Cache(86400)] // 24 hours

How It Works

Cache Key Generation

When you do not pass a key, the key is:

{DeclaringType.FullName}_{MethodName}_{Arguments.ToJson()}

Arguments.ToJson() is the JSON array of the method arguments (Newtonsoft.Json, no indentation). For example, GetProduct(5) on MyApp.Services.ProductService becomes:

MyApp.Services.ProductService_GetProduct_[5]

Search("laptop", 0, 10) becomes:

MyApp.Services.ProductService_Search_["laptop",0,10]

A second Redis key, {cacheKey}_type, stores the result's assembly-qualified type name, with the same TTL.

If you pass an explicit key, that exact string is used for every call, and argument values are not appended.


Type Preservation

Each cached entry is two Redis keys:

Redis key:   MyApp.Services.ProductService_GetProduct_[5]
Redis value: {"Id":5,"Name":"Laptop","Price":999.99}

Redis key:   MyApp.Services.ProductService_GetProduct_[5]_type
Redis value: "MyApp.Models.Product, MyApp, Version=1.0.0.0, ..."

On a cache hit, the value is deserialized to the stored runtime type, so you get a Product back, not an untyped dictionary. If the type cannot be resolved, the entry is treated as a miss and the method runs again.


Compile-Time Weaving

At build time, MethodBoundaryAspect.Fody wraps each [Cache] method with OnEntry and OnExit:

  1. OnEntry: Look up the cache key (explicit or auto-generated). If both the value and the type key exist, deserialize and return immediately.
  2. OnExit (cache miss only): If the return value is not null, serialize it and write both Redis keys with the configured TTL.

[UnCache] runs on exit and deletes both the value key and the _type key. This is described further in How Compile-Time AOP Works.


Real-World Examples

Example 1: Product catalog

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly ShopDbContext _db;

    public ProductsController(ShopDbContext db) => _db = db;

    [Cache(300)]
    [HttpGet("{id}")]
    public async Task<Product> GetProduct(int id)
    {
        return await _db.Products
            .Include(p => p.Category)
            .Include(p => p.Reviews)
            .FirstOrDefaultAsync(p => p.Id == id);
    }

    // Explicit literal key so an update can invalidate this entry.
    // All calls share this one key (the method has no parameters).
    [Cache(60, "featured-products")]
    [HttpGet("featured")]
    public async Task<List<Product>> GetFeaturedProducts()
    {
        return await _db.Products
            .Where(p => p.IsFeatured)
            .OrderByDescending(p => p.SalesCount)
            .Take(10)
            .ToListAsync();
    }

    [Cache(120)]
    [HttpGet("search")]
    public async Task<List<Product>> Search(
        string query,
        int? categoryId,
        decimal? minPrice,
        decimal? maxPrice)
    {
        var queryable = _db.Products.AsQueryable();

        if (!string.IsNullOrEmpty(query))
            queryable = queryable.Where(p => p.Name.Contains(query));

        if (categoryId.HasValue)
            queryable = queryable.Where(p => p.CategoryId == categoryId);

        if (minPrice.HasValue)
            queryable = queryable.Where(p => p.Price >= minPrice);

        if (maxPrice.HasValue)
            queryable = queryable.Where(p => p.Price <= maxPrice);

        return await queryable.ToListAsync();
    }

    // Do not put [Cache] on write operations.
    // [UnCache("featured-products")] deletes that explicit key after the method returns.
    [UnCache("featured-products")]
    [HttpPost]
    public async Task<IActionResult> CreateProduct(Product product)
    {
        _db.Products.Add(product);
        await _db.SaveChangesAsync();
        return Ok(product);
    }
}

[UnCache] without a key deletes only the auto-generated key of the method it is applied to. That does not match a different method such as GetProduct. To invalidate another method's cache, use a shared explicit key as above, or delete the exact auto-generated key (and the _type key) through RedisManagerV1.Database.KeyDelete.


Example 2: Expensive aggregations

public class AnalyticsService
{
    private readonly AppDbContext _db;

    public AnalyticsService(AppDbContext db) => _db = db;

    [Cache(3600)]
    public async Task<SalesSummary> GetDailySales(DateTime date)
    {
        return await _db.Orders
            .Where(o => o.OrderDate.Date == date.Date)
            .GroupBy(o => 1)
            .Select(g => new SalesSummary
            {
                TotalRevenue = g.Sum(o => o.TotalAmount),
                OrderCount = g.Count(),
                AverageOrderValue = g.Average(o => o.TotalAmount)
            })
            .FirstOrDefaultAsync();
    }

    [Cache(86400)]
    public async Task<List<MonthlyRevenue>> GetMonthlyRevenue(int year)
    {
        return await _db.Orders
            .Where(o => o.OrderDate.Year == year)
            .GroupBy(o => o.OrderDate.Month)
            .Select(g => new MonthlyRevenue
            {
                Month = g.Key,
                Revenue = g.Sum(o => o.TotalAmount)
            })
            .OrderBy(m => m.Month)
            .ToListAsync();
    }
}

Example 3: Per-tenant data

Arguments are part of the automatic key, so each tenantId is cached separately:

public class TenantService
{
    private readonly AppDbContext _db;

    public TenantService(AppDbContext db) => _db = db;

    [Cache(600)]
    public async Task<TenantConfig> GetTenantConfig(int tenantId)
    {
        return await _db.TenantConfigs
            .Include(c => c.Settings)
            .FirstOrDefaultAsync(c => c.TenantId == tenantId);
    }

    [Cache(300)]
    public async Task<List<User>> GetTenantUsers(int tenantId)
    {
        return await _db.Users
            .Where(u => u.TenantId == tenantId)
            .ToListAsync();
    }
}

Performance Benchmarks

This repository does not include a benchmark project, so this README does not publish latency, throughput, memory, or cost figures.

A cache hit replaces the method body with a Redis read and deserialization. How much that helps depends on the work you are avoiding and on Redis network latency. Measure against your own endpoints and data.


How Compile-Time AOP Works (Fody Weaving)

Traditional interceptors (for example, runtime proxies) wrap calls at run time and often require virtual methods or a DI container. Chd.Caching uses compile-time weaving: during dotnet build, MethodBoundaryAspect.Fody inserts calls to CacheAttribute.OnEntry / OnExit (and the [UnCache] equivalents) directly into the method.

What that means in practice:

  • You can put the attributes on instance or static methods; they do not need to be virtual.
  • There is no proxy object and no interceptor pipeline to set up at startup.
  • The cache logic itself still runs, including Redis I/O, JSON serialization, and, for Task<T>, a small amount of reflection to unwrap the result.
  • The weaver is shipped inside the Chd.Caching NuGet package. You do not install Fody or add FodyWeavers.xml unless the project already uses Fody (see Installation and Upgrading from earlier versions).

On a cache hit, OnEntry returns the deserialized value and the original method body does not run. On a miss, the method runs, then OnExit stores a non-null result.

How to verify weaving

Build the project and look for these lines (the project name and weaver version may differ):

Chd.Caching: weaving MethodBoundaryAspect into YourProject
Fody/MethodBoundaryAspect: Executing weaver MethodBoundaryAspect v2.0.150

If those lines are missing, [Cache] has no effect. See Troubleshooting.


API Reference

Extension methods

// ASP.NET Core, after WebApplication.CreateBuilder(...).Build()
app.UseRedis();

// Tests or console apps: app may be null. Reads appsettings.json
// (and appsettings.{ASPNETCORE_ENVIRONMENT}.json, if present)
// from the current working directory.
CachingDependenyInjectionExtensions.UseRedis(null);

UseRedis sets RedisManagerV1's connection string from configuration. It does not use the IApplicationBuilder argument beyond accepting it as an extension target.

If Redis:Password is present:

{Redis:Url},abortConnect=false,password={Redis:Password}

Otherwise the connection string is Redis:Url unchanged.

You can also set the connection string directly:

RedisManagerV1.Register("localhost:6379,abortConnect=false,password=my_secret_password");

Cache Attribute

namespace Chd.Caching;

public sealed class CacheAttribute : OnMethodBoundaryAspect
{
    public CacheAttribute(int cacheExpireSecond);
    public CacheAttribute(int cacheExpireSecond, string key);
}
[Cache(60)]
public Product GetProduct(int id) { ... }

[Cache(60, "catalog")] // literal key; all calls share this entry
public List<Product> GetCatalog() { ... }

Supported:

  • Synchronous methods and async Task<T>
  • Primitive, object, and collection return types (null results are not cached)
  • Multiple parameters; they become part of the automatic key
  • Static and instance methods
  • Optional explicit literal key

[Cache] is not useful on void or async Task (non-generic) methods, because there is no value to store.


UnCache Attribute

namespace Chd.Caching;

public sealed class UnCacheAttribute : OnMethodBoundaryAspect
{
    public UnCacheAttribute();
    public UnCacheAttribute(string key);
}
[UnCache("catalog")] // deletes "catalog" and "catalog_type" after the method exits
public void RefreshCatalog() { ... }

[UnCache] // deletes the auto-generated key of RefreshCatalog itself, not of another method
public void RefreshCatalog() { ... }

Use a shared explicit key to clear a [Cache] entry from a different method. The explicit key is a literal; it is not interpolated with argument values.


Redis Manager

namespace Chd.Caching.Redis;

public static class RedisManagerV1
{
    public static IDatabase Database { get; } // StackExchange.Redis
    public static void Register(string server);
}

Database connects on first use with ConnectionMultiplexer.Connect. If UseRedis or Register has not been called, it throws RedisServerNotNullException.

Manual operations use the StackExchange.Redis IDatabase API, for example:

RedisManagerV1.Database.KeyDelete("catalog");
RedisManagerV1.Database.KeyDelete("catalog_type");

There is no DeletePattern, Set, or Get helper on RedisManagerV1.


Troubleshooting

Issue: Cache not applied (method always runs)

Cause: The weaver did not run, or Redis is not used after a successful weave.

Fix:

  1. Do a Clean + Rebuild.
  2. Confirm the build output contains Chd.Caching: weaving MethodBoundaryAspect into <Project> and Fody/MethodBoundaryAspect: Executing weaver MethodBoundaryAspect.
  3. If the project already has FodyWeavers.xml, add <MethodBoundaryAspect />.
  4. If you already installed Fody and MethodBoundaryAspect.Fody yourself, that setup keeps working. See Upgrading from earlier versions.
  5. Call UseRedis() (or UseRedis(null) in tests) before the cached method runs, and make sure Redis is reachable.

Issue: RedisConnectionException / UnableToConnect

Cause: Redis is not running, or Url is wrong.

Fix:

docker ps
docker exec -it redis-cache redis-cli PING
# Expect: PONG

If the server requires a password, pass it with -a:

docker exec -it redis-cache redis-cli -a my_secret_password PING

Url must include the host:

{
  "Redis": {
    "Url": "localhost:6379"
  }
}

A value like ":6379" (host missing) leads to UnableToConnect on :6379:6379. If Redis is published on a different host port (for example 3031 in the included Docker Compose file), use that port in Url.


Issue: NOAUTH Authentication required

Cause: The server expects a password and none was supplied.

Fix: Set Redis:Password in appsettings.json to the server password. If Password is set, keep Url as host:port only.


Issue: Stale data

Cause: The TTL is longer than you want, or an update did not invalidate the entry.

Fix: Lower the TTL, pair writes with [UnCache] using a shared explicit key, or delete the exact key and its _type companion:

RedisManagerV1.Database.KeyDelete(cacheKey);
RedisManagerV1.Database.KeyDelete(cacheKey + "_type");

Best Practices

1. Choose a TTL that matches how often the data changes

[Cache(60)]    // data that changes often
[Cache(300)]   // product details, profiles
[Cache(3600)]  // categories, settings
[Cache(86400)] // historical reports

2. Cache reads, not writes

Do not apply [Cache] to methods that create, update, or delete data. Cache the corresponding read instead:

[Cache(60)]
public async Task<Product> GetProduct(int id)
{
    return await _db.Products.FindAsync(id);
}

3. Invalidate with a shared explicit key

[UnCache] without a key does not clear a different method's automatic key. Give both methods the same literal key:

[Cache(60, "featured-products")]
public async Task<List<Product>> GetFeaturedProducts() { ... }

[UnCache("featured-products")]
public async Task UpdateFeatured()
{
    // update storage
}

For automatic (per-argument) keys, delete the exact key via RedisManagerV1.Database.KeyDelete, including the _type key.

4. Prefer simple parameter types on cached methods

The automatic key contains the JSON of every argument. Large object graphs make large keys and can surprise you if an argument includes values that change on every call (for example, a timestamp).

5. Inspect Redis when you need to see hits and misses

docker exec -it redis-cache redis-cli
INFO stats
MONITOR

FAQ

1. Can I use Chd.Caching with a backend other than Redis?

No. Redis is the only supported backend.

2. Does it work with EF Core change tracking?

Cached entities are deserialized from JSON and are not tracked. To update one, attach it yourself:

var cachedProduct = await GetProduct(5);
_db.Attach(cachedProduct);
_db.Entry(cachedProduct).State = EntityState.Modified;

3. Can I cache void methods?

No. [Cache] stores a return value, and null is not stored. Use a method that returns a value:

[Cache(60)]
public string DoSomething()
{
    // work
    return "result";
}

4. How do I clear the cache?

Delete a specific key (and its type companion):

RedisManagerV1.Database.KeyDelete(cacheKey);
RedisManagerV1.Database.KeyDelete(cacheKey + "_type");

To flush the current Redis database (this deletes everything in that database, not only this application's keys):

docker exec -it redis-cache redis-cli FLUSHDB

RedisManagerV1 has no pattern-delete helper.


Examples & Tests

Working samples, unit tests, load tests and benchmarks for CHD packages are available in the public Chd.Examples repository.


Package Description NuGet
Chd.Common Infrastructure primitives (configuration, encryption, extensions) NuGet
Chd.Min.IO MinIO/S3 object storage with image optimization NuGet
Chd.Logging Structured logging with Serilog (Graylog, MSSQL, file) NuGet

Contributing

Bug reports and feature requests are welcome.

  1. Issues: GitHub Issues
  2. Pull Requests: GitHub Pull Requests

Working samples are in the public Chd.Examples repository.


License

This package is free and open-source under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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
10.0.6 68 11/12/2026
10.0.5 47 11/12/2026
10.0.4 51 11/12/2026
10.0.3 86 11/12/2026
10.0.2 149 9/1/2026
10.0.1 148 8/30/2026
10.0.0 141 8/16/2026
8.6.5 132 9/5/2026
8.6.4 142 8/16/2026
8.6.3 133 8/16/2026
8.6.2 162 3/24/2026
8.6.1 148 3/2/2026
8.6.0 146 2/19/2026
8.5.9 159 1/21/2026
8.5.8 167 1/21/2026
8.5.7 157 1/21/2026