Pinqponq.Cache
1.0.0
Prefix Reserved
See the version list below for details.
dotnet add package Pinqponq.Cache --version 1.0.0
NuGet\Install-Package Pinqponq.Cache -Version 1.0.0
<PackageReference Include="Pinqponq.Cache" Version="1.0.0" />
<PackageVersion Include="Pinqponq.Cache" Version="1.0.0" />
<PackageReference Include="Pinqponq.Cache" />
paket add Pinqponq.Cache --version 1.0.0
#r "nuget: Pinqponq.Cache, 1.0.0"
#:package Pinqponq.Cache@1.0.0
#addin nuget:?package=Pinqponq.Cache&version=1.0.0
#tool nuget:?package=Pinqponq.Cache&version=1.0.0
Pinqponq.Cache
A thin Redis wrapper for .NET: a string/object cache (ICacheService) and a
distributed lock (IDistributedLock) over a single shared StackExchange.Redis
connection multiplexer, plus a ready-made health check. It does not bring in a
second Redis client version or a competing serializer — one connection, one
JSON serializer (System.Text.Json), one set of options.
Install
dotnet add package Pinqponq.Cache
Requirements
- .NET SDK:
net8.0,net9.0, ornet10.0 - A reachable Redis server (standalone, Sentinel, or cluster — anything
StackExchange.Rediscan parse a connection string for)
Quick start
using Pinqponq.Cache;
using Pinqponq.Cache.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddPinqponqCache(redis =>
{
redis.ConnectionString = "localhost:6379,abortConnect=false";
redis.InstanceName = "myapp:";
redis.DefaultTtl = TimeSpan.FromMinutes(10);
});
builder.Services.AddHealthChecks().AddPinqponqRedis();
var app = builder.Build();
app.MapGet("/cache/{key}", async (string key, ICacheService cache) =>
await cache.GetStringAsync(key) is { } value ? Results.Ok(value) : Results.NotFound());
app.Run();
Using the cache and the lock from injected services:
public sealed class OrderService(ICacheService cache, IDistributedLock locks)
{
public async Task<Order?> GetOrderAsync(string orderId, CancellationToken ct)
{
var cached = await cache.GetAsync<Order>($"order:{orderId}", ct);
if (cached is not null)
{
return cached;
}
await using var handle = await locks.AcquireAsync($"order-load:{orderId}", TimeSpan.FromSeconds(30), ct);
if (!handle.Acquired)
{
throw new InvalidOperationException("Could not acquire the load lock.");
}
var order = await LoadFromSourceAsync(orderId, ct);
await cache.SetAsync($"order:{orderId}", order, TimeSpan.FromMinutes(5), ct);
return order;
}
private Task<Order?> LoadFromSourceAsync(string orderId, CancellationToken ct) => Task.FromResult<Order?>(null);
}
public sealed record Order(string Id);
Configuration
RedisOptions, configured through the Action<RedisOptions> delegate passed
to AddPinqponqCache:
| Property | Type | Default | Notes |
|---|---|---|---|
ConnectionString |
string |
"" (required) |
StackExchange.Redis connection string, e.g. host:6379,password=...,defaultDatabase=0,abortConnect=false. |
InstanceName |
string? |
null |
Optional prefix applied to every cache key and to internal lock keys. Useful for multi-tenant or multi-app Redis instances. |
DefaultTtl |
TimeSpan? |
null (no expiry) |
Applied when a Set*Async call omits an explicit expiry. Must be positive when set. |
Options are validated at startup via ValidateOnStart() — an empty
ConnectionString or a non-positive DefaultTtl fails fast instead of
surfacing later as a runtime error.
abortConnect=falseis strongly recommended in the connection string. Without it,ConnectionMultiplexer.ConnectAsynccan block until the connection attempt times out when Redis isn't reachable yet.
Main types
| Type | Kind | Purpose |
|---|---|---|
AddPinqponqCache(Action<RedisOptions>) |
DI extension (IServiceCollection) |
Registers a shared IConnectionMultiplexer, ICacheService, and IDistributedLock. |
AddPinqponqRedis(...) |
DI extension (IHealthChecksBuilder) |
Adds a Redis PING health check (name defaults to "redis"). |
ICacheService |
Interface | GetStringAsync / SetStringAsync, GetAsync<T> / SetAsync<T> (JSON via System.Text.Json), RemoveAsync, ExistsAsync. |
IDistributedLock |
Interface | AcquireAsync(resource, expiry, [options], ct) → ILockHandle. |
ILockHandle |
Interface (IAsyncDisposable) |
Acquired, Token, FencingToken, TryExtendAsync(...); disposing releases the lock if held. |
DistributedLockAcquireOptions |
Options | IssueFencingToken (default true), RenewInterval (watchdog interval; null disables it). |
RedisOptions |
Options | Connection string, key prefix, default TTL. |
RedisCacheService, RedisDistributedLock, RedisHealthCheck |
Implementations | Registered by AddPinqponqCache / AddPinqponqRedis; not usually referenced directly. |
Notes / behavior
- Single connection.
AddPinqponqCacheregisters exactly oneIConnectionMultiplexersingleton (TryAddSingleton, so an app-provided registration wins if added first) and reuses it for the cache and the lock. - JSON serialization.
GetAsync<T>/SetAsync<T>useSystem.Text.Jsonwith default options. A payload that fails to deserialize asT(e.g. schema drift) returnsdefaultfromGetAsync<T>rather than throwing. - Key prefixing. When
InstanceNameis set, cache keys become{InstanceName}{key}and lock keys become{InstanceName}lock:{resource}(with a:fencesuffix for the fencing counter). - Locking is best-effort, not linearizable.
IDistributedLockuses RedisSET NX PX(optionally combined with an atomicINCRfor the fencing token via a Lua script) andLockRelease/LockExtendguarded by a per-acquisition ownership token, so only the holder can release or extend it. This is adequate for reducing duplicate work under normal operation, not a substitute for a consensus-based lock (e.g. Redlock across multiple independent Redis nodes) when correctness under partition is critical. - Fencing tokens are advisory.
DistributedLockAcquireOptions.IssueFencingToken(defaulttrue) mints a monotonically increasinglongvia RedisINCRon successful acquire, exposed asILockHandle.FencingToken. This package only mints and stores the token — enforcing it (e.g. rejecting a database write whose fencing token is stale) is entirely the caller's responsibility. Set it on your resource records and check it before applying a write to get real protection against a lock holder that outlives its TTL (e.g. after a long GC pause). - Renew watchdog. Setting
DistributedLockAcquireOptions.RenewIntervalto a positiveTimeSpanstarts a background timer that callsTryExtendAsyncon that cadence until the handle is disposed; if a renew fails the watchdog logs a warning and stops (the lock will then expire on its own TTL). Leaving itnull(the default) disables the watchdog — you are responsible for extending long-running work yourself viaTryExtendAsync. - Disposal always attempts release.
ILockHandle.DisposeAsyncstops the watchdog (if any) first, then best-effort releases the lock; aRedisExceptionduring release is swallowed since the lock may have already expired or the connection may have dropped. - No repositories, no entities. This package is transport-only: it has no opinion on what you store or how you model it.
Related packages
- Pinqponq.Database.Postgres
- Pinqponq.Database.Mongo
- Pinqponq.Database.Mssql
- Pinqponq.Messaging.RabbitMq
Samples
Try this package in the browser via Pinqponq.Playground — see samples/README.md.
Repository
| 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 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 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. |
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.10)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 10.0.10)
- Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions (>= 10.0.10)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.10)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.10)
- Microsoft.Extensions.Options (>= 10.0.10)
- StackExchange.Redis (>= 2.10.1)
-
net8.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 8.0.11)
- Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions (>= 8.0.11)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
- Microsoft.Extensions.Options (>= 8.0.2)
- StackExchange.Redis (>= 2.10.1)
-
net9.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.18)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 9.0.18)
- Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions (>= 9.0.18)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.18)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.18)
- Microsoft.Extensions.Options (>= 9.0.18)
- StackExchange.Redis (>= 2.10.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.