CacheManager.Redis
2.1.2
See the version list below for details.
dotnet add package CacheManager.Redis --version 2.1.2
NuGet\Install-Package CacheManager.Redis -Version 2.1.2
<PackageReference Include="CacheManager.Redis" Version="2.1.2" />
<PackageVersion Include="CacheManager.Redis" Version="2.1.2" />
<PackageReference Include="CacheManager.Redis" />
paket add CacheManager.Redis --version 2.1.2
#r "nuget: CacheManager.Redis, 2.1.2"
#:package CacheManager.Redis@2.1.2
#addin nuget:?package=CacheManager.Redis&version=2.1.2
#tool nuget:?package=CacheManager.Redis&version=2.1.2
ASP.NET Core Redis Cache Manager
A lightweight abstraction over StackExchange.Redis that offers strongly-typed caching, consistent serialization via System.Text.Json, and ergonomic registration helpers for ASP.NET Core apps.
⭐ If this project saves you time, please consider giving it a star.
Table of Contents
- Installation
- Registering the Cache Manager
- Core API Usage
- Configuring Options
- Sample Application
- Testing the Library
- Performance & Design Notes
- Roadmap
- Dependencies
Installation
Install the package from NuGet:
dotnet add package CacheManager.Redis
Target framework: net8.0.
Registering the Cache Manager
Add the manager during service registration (typically in Program.cs):
using CacheManager.Redis.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRedisCacheManager(
builder.Configuration.GetConnectionString("Redis"),
options =>
{
options.InstanceName = "sample:"; // optional key prefix
options.SerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
};
options.DefaultCacheOptions = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(30)
};
// options.CustomImplementation = typeof(CustomCacheManager<>);
});
This call will:
- Register
StackExchange.Redisusing your connection string. - Expose
IRedisDistributedCacheas a singleton wrapper that carries serializer/options metadata. - Register
IRedisCacheManager<T>as scoped (or a custom implementation if provided).
Tip: The connection string should embed SSL/password settings as needed, e.g.
mycache.redis.cache.windows.net:6380,password=...,ssl=True.
Core API Usage
Inject IRedisCacheManager<T> wherever you need typed access to Redis:
public sealed class MainController : ControllerBase
{
private readonly IRedisCacheManager<Book> _cacheManager;
public MainController(IRedisCacheManager<Book> cacheManager)
=> _cacheManager = cacheManager;
[HttpGet("async")]
public async Task<ActionResult<Book>> GetBookAsync(CancellationToken cancellationToken)
{
if (_cacheManager.TryGet("book-key", out var cachedBook) && cachedBook is not null)
{
return Ok(cachedBook);
}
var book = new Book { Id = 1, Name = "Redis Cache Manager" };
await _cacheManager.SetAsync(
"book-key",
book,
new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromDays(1) },
cancellationToken);
return Ok(book);
}
}
Available operations:
TryGet/GetAsync– read-through access returningboolor nullable values.Set/SetAsync– write-through storage with optionalDistributedCacheEntryOptions.TrySet– best-effort write that returnsfalsefor invalid keys without throwing.Refresh/RefreshAsync– reset sliding expiration.Remove/RemoveAsync– evict cache entries.
Serialization is handled through System.Text.Json; you can override serializer settings globally via registration options.
Configuring Options
RedisCacheMangerOptions (note the historical spelling) allows you to tailor behaviour:
| Option | Description |
|---|---|
InstanceName |
Prefix automatically added to every key stored via this manager. Helpful for multi-tenant or shared Redis deployments. |
SerializerOptions |
Supply a JsonSerializerOptions instance for consistent naming policies, converters, etc. |
DefaultCacheOptions |
Provide default DistributedCacheEntryOptions so that Set/SetAsync calls without explicit options still expire. |
CustomImplementation |
Replace the default RedisCacheManager<T> with your own implementation/decorator. Must implement IRedisCacheManager<T>. |
Custom decorator example
A decorator wraps the default RedisCacheManager<T> to add cross-cutting behaviour (logging, metrics, encryption, etc.) without replacing it. Define a class that implements IRedisCacheManager<T> and delegates to an inner instance:
public sealed class LoggingCacheManager<T> : IRedisCacheManager<T> where T : class
{
private readonly IRedisCacheManager<T> _inner;
private readonly ILogger<LoggingCacheManager<T>> _logger;
public LoggingCacheManager(IRedisCacheManager<T> inner, ILogger<LoggingCacheManager<T>> logger)
{
_inner = inner;
_logger = logger;
}
public bool TryGet(string key, out T? response)
{
var hit = _inner.TryGet(key, out response);
_logger.LogDebug("Cache {Result} for {Key}", hit ? "hit" : "miss", key);
return hit;
}
// Delegate every other IRedisCacheManager<T> member to _inner.
}
Register it with Scrutor's Decorate extension in your application's startup. Add the Scrutor NuGet package to your app (it is not a dependency of CacheManager.Redis itself), then:
builder.Services.AddRedisCacheManager(connectionString);
builder.Services.Decorate(typeof(IRedisCacheManager<>), typeof(LoggingCacheManager<>));
The
options.CustomImplementationsetting is for replacing the default implementation entirely (e.g. a test fake or a fundamentally different backend). Use it instead of Scrutor only when you do not need to delegate to the built-inRedisCacheManager<T>.
Sample Application
The Sample/ folder contains a minimal ASP.NET Core API that exercises the package.
Key endpoints in Sample/Controllers/MainController.cs:
GET /main/async– asynchronous read/write with custom expiration.GET /main/sync– synchronous access using default cache options.POST /main/refresh/{key}– refresh existing entries.DELETE /main/{key}– remove entries safely viaTryRemove.
Update Sample/appsettings.json with a valid Redis connection string before running:
dotnet run --project Sample/Sample.csproj
Testing the Library
Unit tests live under test/CacheManager.Redis.Tests and target net8.0. They cover:
- Serialization helpers (
SerializeExtensions,Helpers.HasValue). - Dependency injection setup (
SetupTests). RedisCacheManagerbehaviours (sync/async, error handling, refresh/remove).
Run the suite with:
dotnet test CacheManager.Redis.sln
Need integration coverage? Spin up a disposable Redis instance (Docker, Azure Cache for Redis emulator, etc.) and add tests under a separate project referencing this library.
Performance & Design Notes
- Binary serialization – the cache manager now uses
JsonSerializer.SerializeToUtf8Bytes/JsonSerializer.Deserializedirectly, avoiding intermediatestringallocations. - Reusable configuration –
AddRedisCacheManagerbootstrapsAddStackExchangeRedisCache, ensuring a singleIConnectionMultiplexerinstance via the built-in provider and registering theIRedisDistributedCachewrapper as a singleton. - Null safety – extension helpers guard against null input and no longer throw when
Type.BaseTypeis null. - Extensibility – provide custom cache managers or decorators for logging, metrics, encryption, etc., using the built-in options hook.
- Observability – collect cache hit/miss metrics and failures by plugging in a decorator (see the Custom decorator example above).
Roadmap
- Automatic cache invalidation hooks (e.g., Redis pub/sub or queue listeners).
- Additional backing stores behind the same abstraction (memcached, in-memory fallbacks).
- Optional middleware/filter packages for transparent caching in MVC or minimal APIs.
- Built-in instrumentation helpers (logging, metrics) with opt-in decorators.
Contributions and feature requests are welcome—open an issue to discuss ideas.
Dependencies
Happy caching! Feel free to reach out or file issues if you run into problems. Contributions of documentation, tests, and new samples are especially appreciated. 🚀
| 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
- Ardalis.GuardClauses (>= 5.0.0)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 8.0.11)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.