Edi.CacheAside.InMemory 2.0.0

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

MemoryCacheAside

A thread-safe implementation of the Cache-Aside pattern using IMemoryCache with support for partitioned cache management.

Overview

MemoryCacheAside provides a wrapper around IMemoryCache that implements the Cache-Aside pattern with the added benefit of cache partitioning. This allows for organized cache management where related cache entries can be grouped together and cleared as a unit.

Features

  • Partitioned Caching: Organize cache entries into logical partitions for better management
  • Thread-Safe Operations: Built with concurrent data structures for safe multi-threaded access
  • Bulk Operations: Clear entire partitions or the entire cache at once
  • Async Support: Provides both synchronous and asynchronous cache operations
  • IDisposable: Properly cleans up resources when disposed

Cache Partitioning

The class maintains a mapping of cache partitions to handle scenarios where you need to clear related cache entries together. This addresses limitations in IMemoryCache where you can't easily enumerate or group cache keys.

Example Partition Structure:

* Key               | Value
* ------------------+--------------------------------------
* PostCountCategory | { "<guid>", "<guid>", ... }
* Post              | { "<guid>", "<guid>", "<guid"> ... }
* General           | { "avatar", ... }

Usage Examples

Basic Usage

// Dependency injection setup services.AddMemoryCache(); services.AddScoped<ICacheAside, MemoryCacheAside>();

public BlogService(ICacheAside cache)
{
    _cache = cache;
}

public async Task<Post> GetPostAsync(Guid postId)
{
    return await _cache.GetOrCreateAsync("Post", postId.ToString(), async entry =>
    {
        entry.SlidingExpiration = TimeSpan.FromMinutes(30);
        return await _repository.GetPostAsync(postId);
    });
}

public void InvalidatePostCache(Guid postId)
{
    _cache.Remove("Post", postId.ToString());
}

public void InvalidateAllPosts()
{
    _cache.Remove("Post");
}

Partitioned Cache Management

// Cache different types of data in separate partitions 
var userProfile = _cache.GetOrCreate("UserProfile", userId, entry => 
{ 
    entry.AbsoluteExpirationRelativeToNow TimeSpan.FromHours(1); 
    return GetUserProfileFromDatabase(userId); 
});

var userSettings = _cache.GetOrCreate("UserSettings", userId, entry => 
{ 
    entry.SlidingExpiration = TimeSpan.FromMinutes(15); 
    return GetUserSettingsFromDatabase(userId); 
});

// Clear all user profile data but keep settings 
_cache.Remove("UserProfile");

// Clear everything 
_cache.Clear();

Thread Safety

The class uses ConcurrentDictionary and ConcurrentBag for thread-safe partition management. All operations are safe to call from multiple threads concurrently.

Performance Considerations

  • ConcurrentBag Duplicates: The partition tracking may contain duplicate keys for performance reasons. This is acceptable as ConcurrentBag prioritizes performance over uniqueness.
  • Memory Usage: Partition metadata is kept in memory until explicitly cleared.
  • Key Removal: Individual key removal from partitions is not performed for efficiency, relying on partition-level or full cache clearing.
Product 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Edi.CacheAside.InMemory:

Repository Stars
EdiWang/Moonglade
Blog system of https://edi.wang, runs on Microsoft Azure
Version Downloads Last Updated
2.0.0 278 8/4/2025
1.3.0 1,001 11/13/2024
1.2.0 1,004 5/19/2024
1.1.0 1,513 10/11/2023
1.0.0 1,150 6/14/2023