Reo.Core.DistributedCache.Abstractions 10.0.354

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

Reo.Core.DistributedCache.Abstractions

Описание пакета

Библиотека предоставляет абстракции и расширения для работы с распределённым кэшированием в .NET-приложениях. Она упрощает управление кэшем, обеспечивая типобезопасные операции, генерацию ключей и интеграцию с Redis. Пакет решает проблему сложного управления кэшем, позволяя разработчикам фокусироваться на бизнес-логике, а не на деталях реализации кэширования.

Основные компоненты

  • ICacheService: Интерфейс для работы с кэшем, предоставляющий методы для установки, получения и удаления данных.
  • CacheKeyExtensions: Класс расширений для генерации уникальных ключей кэша на основе типов сущностей и атрибутов.
  • DistributedCacheExtensions: Расширения для IDistributedCache, добавляющие поддержку типобезопасных операций (JSON и бинарная сериализация).
  • CacheKeyPrefixAttribute: Атрибут для указания префиксов кэш-ключей, позволяющий организовать кэш по категориям.

Требования

  • .NET: Совместим с .NET 6.0 и выше.
  • Зависимости:
    • Microsoft.Extensions.Caching.StackExchangeRedis (для интеграции с Redis).

Установка

Используйте следующие команды для установки пакета:

Install-Package Reo.Core.DistributedCache.Abstractions

или

dotnet add package Reo.Core.DistributedCache.Abstractions

Настройка

Регистрация в DI-контейнере (ASP.NET Core)

Добавьте сервисы в Startup.cs или Program.cs:

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "MyAppCache";
});
services.AddDistributedCache();
services.AddScoped<ICacheService, CacheService>();

Конфигурационные параметры

Укажите настройки Redis в appsettings.json:

{
  "Redis": {
    "ConnectionString": "localhost:6379",
    "InstanceName": "MyAppCache"
  }
}

Использование

Пример 1: Работа с кэшем через ICacheService

public class ProductService
{
    private readonly ICacheService _cacheService;

    public ProductService(ICacheService cacheService)
    {
        _cacheService = cacheService;
    }

    public async Task<Product> GetProductAsync(int id)
    {
        var key = id.BuildCacheKey<Product, int>();
        return await _cacheService.GetTypedAsync<Product>(key);
    }

    public async Task SaveProductAsync(Product product)
    {
        var key = product.Id.BuildCacheKey<Product, int>();
        await _cacheService.SetTypedAsync(key, product, TimeSpan.FromMinutes(10));
    }
}

Пример 2: Генерация кэш-ключа с префиксом

[CacheKeyPrefix("Products")]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Ключ будет: "Products:123"
var key = 123.BuildCacheKey<Product, int>();

Пример 3: Типобезопасное кэширование с Redis

var cache = new RedisCache();
var key = "user:123";
await cache.SetTypedAsync<User>(key, user, TimeSpan.FromHours(1));
var user = await cache.GetTypedAsync<User>(key);

Лицензия

Данный пакет распространяется под лицензией MIT.

Product Compatible and additional computed target framework versions.
.NET 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 (5)

Showing the top 5 NuGet packages that depend on Reo.Core.DistributedCache.Abstractions:

Package Downloads
Reo.Core.IdentityModel

Package Description