Chd.Library.Caching
8.5.10
See the version list below for details.
dotnet add package Chd.Library.Caching --version 8.5.10
NuGet\Install-Package Chd.Library.Caching -Version 8.5.10
<PackageReference Include="Chd.Library.Caching" Version="8.5.10" />
<PackageVersion Include="Chd.Library.Caching" Version="8.5.10" />
<PackageReference Include="Chd.Library.Caching" />
paket add Chd.Library.Caching --version 8.5.10
#r "nuget: Chd.Library.Caching, 8.5.10"
#:package Chd.Library.Caching@8.5.10
#addin nuget:?package=Chd.Library.Caching&version=8.5.10
#tool nuget:?package=Chd.Library.Caching&version=8.5.10
Library.Caching
Chd.Library.Caching is a distributed caching library for .NET 8. It caches method results in Redis with a single [Cache] attribute: no manual cache-key management and no get-or-set boilerplate. Caching is applied automatically at build time. No extra setup is needed.
The public namespace is Library.Caching. The NuGet package id is Chd.Library.Caching.
If you are targeting .NET 10, use Chd.Caching instead. This package is the .NET 8,
Library.Cachingnamespace line.
Table of Contents
- Why Library.Caching?
- Installation
- Quick Start Guide
- Configuration Reference
- How It Works
- Real-World Examples
- Performance Benchmarks
- How Compile-Time AOP Works
- API Reference
- Troubleshooting
- Best Practices
- FAQ
- Examples & Tests
- Related CHD Packages
- Contributing
- License
Why Library.Caching?
Most projects end up with the same get-or-set cache block on every method. Library.Caching replaces that with one attribute.
| Concern | Without Library.Caching | With Library.Caching |
|---|---|---|
| Cache a method result | Write get-or-set code around every call | Add [Cache(60)] |
| Cache key | Build and keep a key by hand | Built from the type, method name and arguments |
| Redis access | Open a connection and serialize yourself | UseRedis() reads appsettings.json and [Cache] talks to Redis |
| Sync and async | Separate paths to maintain | Works with ordinary return types and Task<T> |
Key benefits:
- Applied automatically at build time. No extra setup is needed.
- Redis-backed, so the cache can be shared across process instances.
- Business code stays focused; caching is a single attribute.
- Works with synchronous methods and
Task<T>.
Installation
Requirements: .NET 8 (net8.0) and a Redis server.
Step 1: Install Package
dotnet add package Chd.Library.Caching --version 8.5.10
NuGet Package Manager:
Install-Package Chd.Library.Caching -Version 8.5.10
Package Reference (.csproj):
<PackageReference Include="Chd.Library.Caching" Version="8.5.10" />
That is the only package you need to add. Caching is applied automatically at build time. No extra setup is needed.
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
With a password:
docker run -d --name redis-cache \
-p 6379:6379 \
redis:latest redis-server --requirepass my_secret_password
Without a password (development only):
docker run -d --name redis-cache -p 6379:6379 redis:latest
Step 2: Configure Library.Caching
Add configuration to appsettings.json. Url must include the host and port (for example localhost:6379, not only :6379):
{
"Redis": {
"Url": "localhost:6379",
"Password": "my_secret_password"
}
}
Password is optional. If it is omitted, the connection is made with Url only.
Initialize Redis in Program.cs before cached methods run:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRedis();
app.MapControllers();
app.Run();
UseRedis() reads Redis:Url and Redis:Password from appsettings.json (and appsettings.{Environment}.json) in the current working directory.
Step 3: Add Cache Attribute
using Library.Caching;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _db;
public ProductsController(AppDbContext db) => _db = db;
// Cache for 60 seconds. Each distinct `id` is a separate cache entry.
[Cache(60)]
[HttpGet("{id}")]
public async Task<Product> GetProduct(int id)
{
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)
{
return await _db.Products
.Where(p => p.Name.Contains(query))
.Skip(page * pageSize)
.Take(pageSize)
.ToListAsync();
}
}
Requests to /api/products/5 will:
- First call: run the method, store the result in Redis for 60 seconds.
- Next 60 seconds: return the cached result (the method body does not run).
- After 60 seconds: the entry has expired, so the method runs again.
Null results are not stored.
Configuration Reference
Redis Configuration
| Key | Required | Description |
|---|---|---|
Redis:Url |
Yes | Host and port, for example localhost:6379. |
Redis:Password |
No | If set, it is appended to the StackExchange.Redis connection string as password=... together with abortConnect=false. |
Cache Attribute
[Cache(cacheExpireSecond)]
| Parameter | Type | Description |
|---|---|---|
cacheExpireSecond |
int |
Time to live in seconds, applied to both the value and the companion type key. |
The attribute is in the Library.Caching namespace and can be used on synchronous methods and on methods that return Task or Task<T>.
How It Works
Cache Key Generation
The cache key is built in GetMethodExecutionUniqueId as:
{DeclaringType.FullName}_{Method.Name}_{arguments as JSON}
DeclaringType.FullName is the type that declares the method. The arguments are serialized with the library's JSON helper. Two calls with the same declaring type, method name and argument values share a key; a different argument value is a different entry.
A second Redis key, {cacheKey}_type, stores the result's AssemblyQualifiedName so the value can be deserialized back to the original type.
Type Preservation
On a cache hit, the stored assembly-qualified type name is used to deserialize the JSON value. For Task<T> methods, the deserialized value is wrapped with Task.FromResult.
Compile-Time Weaving
During dotnet build, [Cache] is applied to the method at compile time. 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 with the given TTL.
Real-World Examples
Example 1: Product catalog
using Library.Caching;
public class ProductService
{
private readonly AppDbContext _db;
public ProductService(AppDbContext db) => _db = db;
[Cache(60)]
public Task<Product?> GetByIdAsync(int id)
=> _db.Products.FirstOrDefaultAsync(p => p.Id == id);
}
Example 2: Expensive aggregations
using Library.Caching;
public class ReportService
{
[Cache(300)]
public async Task<SalesSummary> GetDailySales(DateTime day)
{
// Heavy query; result is reused for 5 minutes per distinct `day`.
return await _db.Orders
.Where(o => o.Date == day.Date)
.GroupBy(_ => 1)
.Select(g => new SalesSummary { Count = g.Count(), Total = g.Sum(o => o.Amount) })
.FirstAsync();
}
}
Example 3: Per-tenant data
using Library.Caching;
public class TenantCatalog
{
[Cache(120)]
public Task<List<Item>> ListItems(string tenantId)
=> _db.Items.Where(i => i.TenantId == tenantId).ToListAsync();
}
Because tenantId is part of the method arguments, each tenant gets its own cache entry.
Performance Benchmarks
This repository does not include a benchmark project, so this README does not publish latency, throughput, memory, or cost figures. In general, a Redis cache hit is cheaper than repeating a database or remote call; measure that in your own environment if you need numbers.
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. Library.Caching applies [Cache] at compile time: during dotnet build, calls to CacheAttribute.OnEntry and OnExit are inserted directly into the method.
This is applied automatically at build time. No extra setup is needed. If the project already has a FodyWeavers.xml file, that file must contain <MethodBoundaryAspect />. See Installation and Upgrading from earlier versions.
To confirm that weaving ran, do a full Rebuild and check the build output. For a new project without its own Fody install, you should see a line similar to Chd.Library.Caching: weaving MethodBoundaryAspect into .... You can also inspect the built assembly: a woven [Cache] method is larger than a plain method body and calls into CacheAttribute.
API Reference
Extension methods
UseRedis is defined on IApplicationBuilder and WebApplication (global namespace):
app.UseRedis();
It reads Redis:Url and Redis:Password from appsettings.json in the current working directory and stores the connection string for RedisManagerV1. Call it during startup, before any [Cache] method runs.
Cache Attribute
namespace Library.Caching;
public sealed class CacheAttribute : OnMethodBoundaryAspect
{
public CacheAttribute(int cacheExpireSecond);
}
Redis Manager
Library.Caching.Redis.RedisManagerV1 is the Redis entry point used by [Cache]. Public members:
| Member | Description |
|---|---|
Register(string server) |
Sets the connection string directly, as an alternative to UseRedis(). |
Database |
The StackExchange.Redis IDatabase. Throws RedisServerNotNullException if UseRedis() or Register has not been called. |
UserName / Password |
Public properties; UseRedis() does not set them. The password from configuration is written into the connection string instead. |
There is no UnCache attribute in this package. To remove an entry before it expires, use RedisManagerV1.Database with the key format described in Cache Key Generation, or wait for the TTL.
Troubleshooting
Issue: Cache not applied (method always runs)
- Run a Clean and a full Rebuild (not only Build).
- If the project has a
FodyWeavers.xmlfile, make sure it contains<MethodBoundaryAspect />. - Call
UseRedis()(orRedisManagerV1.Register) before the cached method runs, and make sure Redis is reachable. - Remember that null results are not cached, so a method that returns
nullwill run again on the next call.
Issue: RedisConnectionException / UnableToConnect
- Check that Redis is running and that
Redis:Urlis a host and port, for examplelocalhost:6379. - A value such as
:6379(no host) will not connect. - From a shell:
redis-cli -h localhost -p 6379 ping— expectPONG.
Issue: NOAUTH Authentication required
The server requires a password and Redis:Password is missing or wrong. Set it in appsettings.json to match the server, or disable requirepass on a local development server.
Issue: RedisServerNotNullException
UseRedis() was not called, or Redis:Url was not found in appsettings.json in the current working directory. The exception message asks you to call UseRedis() at startup.
Issue: Stale data
The cached value is served until the TTL given to [Cache] expires. Lower the TTL, or delete the Redis key if you need the next call to run the method immediately.
Best Practices
1. Choose a TTL that matches how often the data changes
Short-lived data should use a short TTL. Relatively stable lookups can use a longer one.
2. Cache reads, not writes
Put [Cache] on query methods. For create/update/delete methods, let the cached read expire (or delete its Redis key) so clients do not keep seeing old data.
3. Prefer simple parameter types on cached methods
The cache key includes the JSON of the arguments. Simple values (ids, strings, numbers) produce stable keys. Avoid passing large object graphs or values that change on every call (for example a DateTime.Now) if you want hits.
4. Inspect Redis when you need to see hits and misses
Use redis-cli (or another Redis client) to list keys and TTLs while you test.
FAQ
1. Can I use Library.Caching with a backend other than Redis?
No. This package uses Redis through StackExchange.Redis.
2. Does it work with EF Core change tracking?
Cached values are serialized to JSON and deserialized on a hit, so you get a new object, not a tracked entity. That is usually what you want for read models. Do not assume a cached entity is attached to a DbContext.
3. Can I cache void methods?
A synchronous void method, or a method that returns a non-generic Task, has no result to store. OnExit skips a null result, so there is nothing useful to cache. Use [Cache] on methods that return a value (including Task<T>).
4. How do I clear the cache?
This package has no invalidation attribute. Wait for the TTL, or delete the Redis key (see Cache Key Generation) through RedisManagerV1.Database.
5. Does this work in a class library, not only in ASP.NET Core?
Yes, as long as the consumer is net8.0, you call UseRedis() or RedisManagerV1.Register before the cached method runs, and Redis is reachable. UseRedis() still reads appsettings.json from the current working directory.
Examples & Tests
Working samples, unit tests, load tests and benchmarks for CHD packages are available in the public Chd.Examples repository.
Related CHD Packages
| Package | Description | NuGet |
|---|---|---|
| Chd.Library.Caching | This package (.NET 8, Library.Caching namespace) |
NuGet |
| Chd.Caching | .NET 10 package in the Chd.Caching namespace |
NuGet |
| Chd.Library.Logging | .NET 8 logging with a [Logged] attribute |
NuGet |
Contributing
Bug reports and feature requests are welcome.
License
This package is free and open-source under the MIT License.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. 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. |
-
net8.0
- Chd.Library.Common (>= 8.7.3)
- MethodBoundaryAspect.Fody (>= 2.0.150)
- Serilog.Settings.Configuration (>= 8.0.0)
- StackExchange.Redis (>= 2.7.17)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.