In-Memory Caching
In-memory caching is the fastest and simplest way to accelerate your .NET applications—no external dependencies, no distributed network overhead, just lightning-fast lookups directly from your server’s memory.
REN.Kit.CacheKit makes in-memory caching easy and production-ready, with flexible expiration strategies and a robust interface you can use in any .NET 8 or .NET 9 project.
1. Configuration: Just Add to Your appsettings.json
appsettings.json
To get started, simply add the following section to your appsettings.json
:
"CacheConfiguration": {
"InMemoryConfiguration": {
"TimeConfiguration": {
"AbsoluteExpirationInHours": 12,
"SlidingExpirationInMinutes": 30
}
}
}
AbsoluteExpirationInHours
: The maximum lifetime for any cached item, regardless of access.SlidingExpirationInMinutes
: How long an item stays alive since its last access—great for keeping hot data fresh.
You can fine-tune these values to match your project’s requirements.
2. Service Registration
After configuring your cache settings, register the required REN.Kit in-memory services in your Program.cs
:
builder.Services.AddRENCaching(RegisterRENCaching.CacheType.InMemory);
You’re now ready to inject IRENCacheService
anywhere in your codebase and start caching like a pro. And here is the content of the AddRENCaching method:
public static void AddRENCaching(this IServiceCollection services, CacheType cacheType)
{
switch (cacheType)
{
case CacheType.InMemory:
AddInMemoryRENCache<RENInMemoryCacheService>(services);
break;
case CacheType.Redis:
AddRedisRENCache<RENRedisCacheService>(services);
break;
default:
throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null);
}
}
Why Choose In-Memory Cache?
Ultra-fast: All data is kept in RAM, with near-zero latency.
Zero setup: No external servers, just plug and play.
Perfect for: Session data, temporary tokens, application-wide settings, or anything that doesn’t need to be shared across servers.
Pro Tip:
In-memory cache is ideal for single-instance or development environments. For distributed or cloud setups, check out the Redis Cache section!
Why is Clear() Not Supported in In-Memory Cache?
You might notice that attempting to clear all cache entries when using the in-memory cache will result in an exception. This is because .NET’s IMemoryCache does not natively support a global “clear all” operation—by design, it provides only key-based access and removal.
If your application requires clearing all cached items at once, you must implement manual key tracking within your own cache service. Only then can you enumerate and remove every key explicitly.
Note: This limitation is intentional, as IMemoryCache is optimized for lightweight, high-speed caching scenarios where global clearing is rarely needed. For distributed scenarios or advanced cache management (including global clear), consider using Redis caching with REN.Kit.
Last updated