Moclawr.Services.Caching 2.1.0

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

Moclawr.Services.Caching

NuGet

Overview

Moclawr.Services.Caching provides a flexible caching solution for .NET applications, with support for both Redis and in-memory caching strategies. It offers a consistent API across different caching providers, making it easy to implement efficient data caching in your applications.

Features

  • Multiple Cache Providers:
    • Redis distributed cache support
    • In-memory cache for development/testing
  • Flexible API: Common interface for all cache operations
  • Advanced Key Management:
    • Pattern-based cache key operations
    • Various search operators (StartsWith, EndsWith, Contains, Exact)
  • Type-Safe Operations: Generic methods for type-safe cache interactions
  • Expiration Control: Set custom expiration times for cached items
  • Bulk Operations: Remove multiple cache entries by pattern
  • Seamless Integration: Easy integration with ASP.NET Core dependency injection

Installation

Install the package via NuGet Package Manager:

dotnet add package Moclawr.Services.Caching

Usage

Configure Redis Caching

In your Program.cs or Startup.cs:

using Services.Caching;

// Add Redis caching
builder.Services.AddRedisCache(builder.Configuration);

Configuration in appsettings.json:

{
  "Redis": {
    "Connection": "localhost:6379",
    "InstanceName": "MyApp:",
    "Database": 0,
    "DefaultCacheTime": 60
  }
}

Using the Cache Service

Inject and use the IRedisServices interface in your services:

using Services.Caching.Redis;

public class ProductService
{
    private readonly IRedisServices _redisServices;
    
    public ProductService(IRedisServices redisServices)
    {
        _redisServices = redisServices;
    }
    
    public async Task<Product> GetProductByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        // Try to get from cache first
        var cacheKey = $"product:{id}";
        var cachedProduct = await _redisServices.GetCacheValueAsync<Product>(cacheKey, cancellationToken);
        
        if (cachedProduct != null)
        {
            return cachedProduct;
        }
        
        // If not in cache, get from database
        var product = await _productRepository.GetByIdAsync(id, cancellationToken);
        
        // Cache the result for 30 minutes
        if (product != null)
        {
            await _redisServices.SetCacheValueAsync(cacheKey, product, 30, cancellationToken);
        }
        
        return product;
    }
    
    public async Task UpdateProductAsync(Product product, CancellationToken cancellationToken = default)
    {
        // Update in database
        await _productRepository.UpdateAsync(product, cancellationToken);
        
        // Update in cache
        var cacheKey = $"product:{product.Id}";
        await _redisServices.SetCacheValueAsync(cacheKey, product, 30, cancellationToken);
    }
    
    public async Task InvalidateProductCacheAsync(int id, CancellationToken cancellationToken = default)
    {
        var cacheKey = $"product:{id}";
        await _redisServices.RemoveCacheValueAsync(cacheKey, cancellationToken);
    }
    
    public async Task InvalidateAllProductCacheAsync(CancellationToken cancellationToken = default)
    {
        // Remove all keys starting with "product:"
        await _redisServices.RemoveCacheRangeAsync(
            "product:", 
            Core.Constants.CacheKeySearchOperator.StartsWith, 
            cancellationToken
        );
    }
}

Advanced Cache Operations

Remove cache entries by pattern:

// Remove all cache entries for a specific user
await _redisServices.RemoveCacheRangeAsync(
    $"user:{userId}:",
    Core.Constants.CacheKeySearchOperator.StartsWith
);

// Remove all cache entries containing a specific term
await _redisServices.RemoveCacheRangeAsync(
    "product",
    Core.Constants.CacheKeySearchOperator.Contains
);

// Remove cache entries with exact match
await _redisServices.RemoveCacheRangeAsync(
    "global:settings",
    Core.Constants.CacheKeySearchOperator.Exact
);

Integration with Other Moclawr Packages

This package works seamlessly with other packages in the Moclawr ecosystem:

  • Moclawr.Core: Provides configuration models, constants, and cache key search operators
  • Moclawr.Host: Can be used together for building complete API solutions with health checks
  • Moclawr.EfCore: Perfect for caching Entity Framework Core query results and repositories
  • Moclawr.MongoDb: Use with MongoDB repositories for caching document queries
  • Moclawr.MinimalAPI: Integrates with endpoint handlers for response caching
  • Moclawr.Services.External: Cache external API responses and reduce third-party calls

Requirements

  • .NET 9.0 or higher
  • StackExchange.Redis 2.8.37 or higher
  • Microsoft.Extensions.Caching.StackExchangeRedis 9.0.0 or higher

License

This package is licensed under the MIT License.

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 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.

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
2.1.0 284 5/28/2025
2.0.0 74 5/24/2025
1.0.3 64 5/24/2025
1.0.2 141 5/22/2025
1.0.1 141 5/21/2025
1.0.0 218 5/15/2025

Added improved XML documentation and bug fixes.