EmfGlobalCaching 1.0.16

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

EmfGlobalCaching

NuGet License: MIT

Author / Yazar: Mehmet SEYİTOĞLU
Company / Şirket: EMF BİLGİSAYAR YAZILIM YÖNETİM VE DANIŞMANLIK HİZMETLERİ
Target Framework: .NET 10
License / Lisans: MIT


🇹🇷 Türkçe Dokümantasyon

Genel Bakış

EmfGlobalCaching, .NET uygulamalarında Memory Cache ve Redis Cache desteği sunan, MediatR pipeline davranışı üzerinden otomatik önbellekleme sağlayan genel amaçlı bir önbellekleme kütüphanesidir.

Ne İşe Yarar?

  • ✅ Memory Cache ve Redis Cache arasında kolayca geçiş yapabilme
  • ✅ MediatR pipeline üzerinden otomatik önbellekleme (CachingBehavior)
  • ✅ Kullanıcı bazlı cache takibi (UserContext)
  • ✅ Grup bazlı cache yönetimi (toplu silme)
  • ✅ Pattern bazlı cache silme
  • ✅ Null ve boş veri önbellekleme koruması
  • IPaginate<T> desteği (EFGenericUnitOfWork uyumlu)
  • ✅ Thread-safe cache işlemleri
  • ✅ Yapılandırılabilir cache süresi

Kurulum

dotnet add package EmfGlobalCaching

DI Kaydı (Dependency Injection)

Memory Cache Kullanımı
// Program.cs

// 1. Cache konfigürasyonunu ekle
builder.Services.Configure<CacheConfig>(options =>
{
    options.CacheProvider = "Memory";
    options.DefaultCacheDuration = TimeSpan.FromMinutes(30);
});

// 2. Memory Cache servislerini kaydet
builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<UserContext>();
builder.Services.AddScoped<ICacheService, MemoryCacheService>();
builder.Services.AddScoped<CacheManager>();

// 3. MediatR ile CachingBehavior'ı kaydet
builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
    cfg.AddOpenBehavior(typeof(CachingBehavior<,>));
});
Redis Cache Kullanımı
// Program.cs

// 1. Redis bağlantısını yapılandır
var redisConnectionString = builder.Configuration.GetConnectionString("Redis");
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnectionString;
});
builder.Services.AddSingleton(ConnectionMultiplexer.Connect(redisConnectionString));

// 2. Cache konfigürasyonunu ekle
builder.Services.Configure<CacheConfig>(options =>
{
    options.CacheProvider = "Redis";
    options.DefaultCacheDuration = TimeSpan.FromMinutes(60);
});

// 3. Redis Cache servislerini kaydet
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<UserContext>();
builder.Services.AddScoped<ICacheService, RedisCacheService>();
builder.Services.AddScoped<CacheManager>();

// 4. MediatR ile CachingBehavior'ı kaydet
builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
    cfg.AddOpenBehavior(typeof(CachingBehavior<,>));
});

appsettings.json Konfigürasyonu

{
  "CacheConfig": {
    "CacheProvider": "Memory",
    "DefaultCacheDuration": "00:30:00"
  },
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  }
}

Temel Kullanım Örnekleri

MediatR ile Otomatik Önbellekleme

MediatR query'lerinize ICachable interface'ini ekleyerek otomatik önbellekleme sağlayın:

// 1. Query sınıfınıza ICachable ekleyin
public class GetProductsQuery : IRequest<IEnumerable<Product>>, ICachable
{
    public int CategoryId { get; set; }

    // ICachable implementasyonu
    public string CacheKey => $"Products_Category_{CategoryId}";
    public TimeSpan? CacheDuration => TimeSpan.FromMinutes(15);
    public string CacheGroup => "Products";
}

// 2. Handler'ınız değişmez, CachingBehavior otomatik çalışır
public class GetProductsHandler : IRequestHandler<GetProductsQuery, IEnumerable<Product>>
{
    private readonly IUnitOfWork _unitOfWork;

    public GetProductsHandler(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task<IEnumerable<Product>> Handle(GetProductsQuery request, CancellationToken ct)
    {
        var repo = _unitOfWork.GetRepository<Product, int>();
        return await repo.GetAllAsync(p => p.CategoryId == request.CategoryId);
    }
}

Nasıl çalışır?

  1. İlk çağrıda cache boş → Handler çalışır → Sonuç hem döndürülür hem cache'lenir
  2. Sonraki çağrılarda cache dolu → Direkt cache'den döndürülür (handler atlanır)
  3. Cache süresi dolduktan sonra → Tekrar handler çalışır
CacheManager ile Manuel Önbellekleme
public class ProductService
{
    private readonly CacheManager _cacheManager;

    public ProductService(CacheManager cacheManager)
    {
        _cacheManager = cacheManager;
    }

    // Cache'den veri getir
    public List<Product> GetCachedProducts(int categoryId)
    {
        var cacheKey = $"Products_{categoryId}";
        return _cacheManager.Get<List<Product>>(cacheKey, "Products");
    }

    // Cache'e veri yaz
    public void CacheProducts(List<Product> products, int categoryId)
    {
        var cacheKey = $"Products_{categoryId}";
        _cacheManager.Set(cacheKey, products, TimeSpan.FromMinutes(30), "Products");
    }

    // Tek bir cache anahtarını sil
    public void RemoveProductCache(int categoryId)
    {
        var cacheKey = $"Products_Products_{categoryId}";
        _cacheManager.Remove(cacheKey);
    }

    // Bir gruptaki tüm cache'i sil
    public void ClearAllProductsCache()
    {
        _cacheManager.RemoveGroup("Products");
    }
}
Pagination ile Cache
public class GetPagedProductsQuery : IRequest<IPaginate<Product>>, ICachable
{
    public int PageIndex { get; set; }
    public int PageSize { get; set; }

    public string CacheKey => $"Products_Page_{PageIndex}_Size_{PageSize}";
    public TimeSpan? CacheDuration => TimeSpan.FromMinutes(10);
    public string CacheGroup => "ProductPages";
}

🇬🇧 English Documentation

Overview

EmfGlobalCaching is a general-purpose caching library for .NET applications that provides Memory Cache and Redis Cache support with automatic caching through the MediatR pipeline behavior.

What Does It Do?

  • ✅ Easily switch between Memory Cache and Redis Cache
  • ✅ Automatic caching via MediatR pipeline (CachingBehavior)
  • ✅ User-based cache tracking (UserContext)
  • ✅ Group-based cache management (bulk removal)
  • ✅ Pattern-based cache removal
  • ✅ Protection against caching null or empty data
  • IPaginate<T> support (EFGenericUnitOfWork compatible)
  • ✅ Thread-safe cache operations
  • ✅ Configurable cache duration

Installation

dotnet add package EmfGlobalCaching

DI Registration (Dependency Injection)

Memory Cache Setup
// Program.cs

// 1. Add cache configuration
builder.Services.Configure<CacheConfig>(options =>
{
    options.CacheProvider = "Memory";
    options.DefaultCacheDuration = TimeSpan.FromMinutes(30);
});

// 2. Register Memory Cache services
builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<UserContext>();
builder.Services.AddScoped<ICacheService, MemoryCacheService>();
builder.Services.AddScoped<CacheManager>();

// 3. Register CachingBehavior with MediatR
builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
    cfg.AddOpenBehavior(typeof(CachingBehavior<,>));
});
Redis Cache Setup
// Program.cs

// 1. Configure Redis connection
var redisConnectionString = builder.Configuration.GetConnectionString("Redis");
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnectionString;
});
builder.Services.AddSingleton(ConnectionMultiplexer.Connect(redisConnectionString));

// 2. Add cache configuration
builder.Services.Configure<CacheConfig>(options =>
{
    options.CacheProvider = "Redis";
    options.DefaultCacheDuration = TimeSpan.FromMinutes(60);
});

// 3. Register Redis Cache services
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<UserContext>();
builder.Services.AddScoped<ICacheService, RedisCacheService>();
builder.Services.AddScoped<CacheManager>();

// 4. Register CachingBehavior with MediatR
builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
    cfg.AddOpenBehavior(typeof(CachingBehavior<,>));
});

appsettings.json Configuration

{
  "CacheConfig": {
    "CacheProvider": "Memory",
    "DefaultCacheDuration": "00:30:00"
  },
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  }
}

Basic Usage Examples

Automatic Caching with MediatR

Add the ICachable interface to your MediatR queries for automatic caching:

// 1. Add ICachable to your query class
public class GetProductsQuery : IRequest<IEnumerable<Product>>, ICachable
{
    public int CategoryId { get; set; }

    // ICachable implementation
    public string CacheKey => $"Products_Category_{CategoryId}";
    public TimeSpan? CacheDuration => TimeSpan.FromMinutes(15);
    public string CacheGroup => "Products";
}

// 2. Your handler remains unchanged, CachingBehavior works automatically
public class GetProductsHandler : IRequestHandler<GetProductsQuery, IEnumerable<Product>>
{
    private readonly IUnitOfWork _unitOfWork;

    public GetProductsHandler(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task<IEnumerable<Product>> Handle(GetProductsQuery request, CancellationToken ct)
    {
        var repo = _unitOfWork.GetRepository<Product, int>();
        return await repo.GetAllAsync(p => p.CategoryId == request.CategoryId);
    }
}

How it works:

  1. First call → cache is empty → Handler executes → Result is returned and cached
  2. Subsequent calls → cache is populated → Returns directly from cache (handler is skipped)
  3. After cache expires → Handler executes again
Manual Caching with CacheManager
public class ProductService
{
    private readonly CacheManager _cacheManager;

    public ProductService(CacheManager cacheManager)
    {
        _cacheManager = cacheManager;
    }

    // Get data from cache
    public List<Product> GetCachedProducts(int categoryId)
    {
        var cacheKey = $"Products_{categoryId}";
        return _cacheManager.Get<List<Product>>(cacheKey, "Products");
    }

    // Write data to cache
    public void CacheProducts(List<Product> products, int categoryId)
    {
        var cacheKey = $"Products_{categoryId}";
        _cacheManager.Set(cacheKey, products, TimeSpan.FromMinutes(30), "Products");
    }

    // Remove a single cache key
    public void RemoveProductCache(int categoryId)
    {
        var cacheKey = $"Products_Products_{categoryId}";
        _cacheManager.Remove(cacheKey);
    }

    // Remove all cache in a group
    public void ClearAllProductsCache()
    {
        _cacheManager.RemoveGroup("Products");
    }
}
Pagination with Cache
public class GetPagedProductsQuery : IRequest<IPaginate<Product>>, ICachable
{
    public int PageIndex { get; set; }
    public int PageSize { get; set; }

    public string CacheKey => $"Products_Page_{PageIndex}_Size_{PageSize}";
    public TimeSpan? CacheDuration => TimeSpan.FromMinutes(10);
    public string CacheGroup => "ProductPages";
}

API Reference / API Referansı

Class / Interface Description (EN) Açıklama (TR)
ICacheService Cache service abstraction (Memory/Redis) Cache servis soyutlaması (Memory/Redis)
MemoryCacheService In-memory cache implementation Bellek içi cache implementasyonu
RedisCacheService Redis distributed cache implementation Redis dağıtık cache implementasyonu
CacheManager High-level cache manager with group support Grup desteği ile üst düzey cache yöneticisi
CachingBehavior<TRequest, TResponse> MediatR pipeline behavior for auto-caching Otomatik önbellekleme için MediatR pipeline davranışı
ICachable Interface to mark cacheable requests Önbellenebilir istekleri işaretlemek için interface
CacheConfig Cache configuration (provider, duration) Cache yapılandırması (sağlayıcı, süre)
CachedData<T> Wrapper for cached data with metadata Metadata ile cache'lenmiş veri sarmalayıcı
UserContext Resolves current user from HttpContext HttpContext'ten geçerli kullanıcıyı çözümler

Dependencies / Bağımlılıklar

  • EFGenericUnitOfWork (1.0.42)
  • MediatR (14.1.0)
  • Microsoft.Extensions.Caching.Memory (10.0.5)
  • Microsoft.Extensions.Caching.StackExchangeRedis (10.0.5)
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

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
1.0.16 6 4/27/2026
1.0.15 84 4/20/2026
1.0.14 105 3/16/2026
1.0.13 211 7/27/2025
1.0.12 182 7/27/2025
1.0.11 558 3/24/2025
1.0.10 405 3/24/2025
1.0.8 425 3/24/2025
1.0.7 387 3/24/2025
1.0.6 165 1/30/2025
1.0.5 201 9/9/2024
1.0.4 207 7/23/2024
1.0.3 184 7/16/2024
1.0.2 169 7/15/2024
1.0.1 168 7/15/2024
1.0.0 177 7/15/2024

Initial release with support for global caching using Memory Cache and Redis, integrated with MediatR, Entity Framework Core, Repository Pattern, UnitOfWork Pattern, and SoftDelete functionality.