AspNetCoreCacheKit 3.0.0

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

AspNetCoreCacheKit

NuGet Publish to NuGet License: MIT GitHub Sponsors Changelog

A lightweight caching library for ASP.NET Core featuring group-based keys, per-entry and per-group duration, configurable via appsettings.json, and a DI-ready design that wraps IMemoryCache in a clean, testable abstraction.

Why AspNetCoreCacheKit? IMemoryCache is powerful but low-level. AspNetCoreCacheKit adds group-based key management, per-group and per-entry expiration, appsettings.json configuration, and a consistent type-safe API that makes caching easy to use and easy to mock in tests.


โœจ Features

  • ๐Ÿ”‘ Group-based keys โ€” organise cache entries with prefixes like "users:123"
  • โšก GetOrCreate and GetOrCreateAsync โ€” read-through pattern out of the box
  • โฑ๏ธ Per-group and per-entry duration โ€” fine-grained expiration control
  • ๐Ÿ—‘๏ธ Delete โ€” remove a single entry by key or group + key
  • โœ… Configuration validation with DataAnnotations
  • ๐Ÿ“ Nullable reference types and generic type-safe Set<T> support
  • ๐ŸŽ›๏ธ appsettings.json configuration with sensible defaults
  • ๐Ÿงช DI-ready โ€” register with one line, mock ICacheService in tests

๐Ÿ“‹ Requirements

Requirement Minimum version
.NET 9.0+
ASP.NET Core 9.0+

๐Ÿš€ Installation

dotnet add package AspNetCoreCacheKit

๐ŸŽฏ Quick Start

1. Configure appsettings.json

{
  "CacheOptions": {
    "IsEnabled": true,
    "DurationMinutes": 60,
    "GroupDurations": {
      "users": 30,
      "tokens": 5,
      "countries": 1440
    }
  }
}

All duration values are expressed in minutes. GroupDurations is optional โ€” groups without an entry use the global DurationMinutes.

2. Register services

// With appsettings.json
builder.Services.AddAspNetCoreCacheKit(builder.Configuration);

// Without appsettings (uses defaults)
builder.Services.AddAspNetCoreCacheKit();

3. Inject and use

[ApiController]
public class UsersController : ControllerBase
{
    private readonly ICacheService _cache;

    public UsersController(ICacheService cache)
    {
        _cache = cache;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser(int id, CancellationToken ct)
    {
        // Uses GroupDurations["users"] = 30 min from appsettings
        var user = await _cache.GetOrCreateAsync(
            "users",
            id.ToString(),
            _ => GetUserFromDb(id),
            ct: ct);

        return user is null ? NotFound() : Ok(user);
    }
}

๐Ÿ“š API Reference

Duration priority

Every method that writes to the cache resolves the expiration following this priority chain โ€” first wins:

  1. duration parameter passed explicitly to the method
  2. GroupDurations[groupKey] configured in appsettings.json
  3. Global DurationMinutes from appsettings.json
// 1. Explicit duration wins โ€” cached for 2 minutes regardless of everything else
await _cache.GetOrCreateAsync("tokens", userId, _ => GenerateTokenAsync(), TimeSpan.FromMinutes(2));

// 2. No explicit duration โ€” uses GroupDurations["users"] = 30 min from appsettings
await _cache.GetOrCreateAsync("users", "42", _ => GetUserFromDb(42));

// 3. No explicit duration, no group config โ€” uses global DurationMinutes = 60 min
await _cache.GetOrCreateAsync("misc", "key", _ => LoadSomethingAsync());

GetOrCreateAsync โ€” async read-through

// With group โ€” uses GroupDurations["users"] or global fallback
var user = await _cache.GetOrCreateAsync("users", "42", _ => GetUserFromDb(42), ct: ct);

// With group + explicit duration override
var token = await _cache.GetOrCreateAsync(
    "tokens", userId,
    _ => GenerateTokenAsync(userId),
    duration: TimeSpan.FromMinutes(5),
    ct);

// Without group key
var config = await _cache.GetOrCreateAsync("app:config", _ => LoadConfigAsync(), ct: ct);

GetOrCreate โ€” sync read-through

// Uses GroupDurations["countries"] = 1440 min from appsettings
var countries = _cache.GetOrCreate("countries", () => LoadCountries());

// Explicit override
var result = _cache.GetOrCreate("countries", "IT", () => LoadItaly(), TimeSpan.FromHours(2));

Set โ€” explicit write

_cache.Set("users", "42", user);                                   // group duration or global
_cache.Set("users", "42", user, TimeSpan.FromMinutes(10));         // explicit override

Delete โ€” remove an entry

_cache.Delete("users", "42");
_cache.Delete("app:config");

โš™๏ธ Configuration options

Option Type Default Description
IsEnabled bool true Enables or disables caching entirely. When false, factories are always invoked.
DurationMinutes int 60 Global default cache duration in minutes.
GroupDurations Dictionary<string, int> {} Per-group durations in minutes. Key = group name, Value = duration in minutes.

Setting IsEnabled: false is useful in development or testing environments where you want to bypass the cache without changing code.


๐Ÿงช Testing

ICacheService is a plain interface โ€” mock it directly in unit tests:

var cacheMock = new Mock<ICacheService>();

cacheMock
    .Setup(c => c.GetOrCreateAsync(
        "users", "1",
        It.IsAny<Func<ICacheEntry, Task<User>>>(),
        It.IsAny<TimeSpan?>(),
        It.IsAny<CancellationToken>()))
    .ReturnsAsync(new User { Id = 1, Name = "Simone" });

โค๏ธ Support

If you find AspNetCoreCacheKit useful, consider sponsoring its development.

Sponsor simoneM93


๐Ÿ“„ License

MIT โ€” see LICENSE for details.

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 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
3.0.0 34 3/25/2026
2.0.0 35 3/24/2026
1.0.0 89 2/25/2026