IDistributedCache Abstraction
Cache data across multiple servers.
IDistributedCache Abstraction is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Distributed Caching?
An in-memory cache lives inside a single process, so it is lost on restart and not shared across servers. A distributed cache lives in an external store (like Redis) that every instance of your app can read and write, making caching consistent across a scaled-out deployment.
The IDistributedCache Interface
ASP.NET Core abstracts distributed caching behind IDistributedCache in Microsoft.Extensions.Caching.Distributed. Your code depends on this interface, not on Redis directly, so you can swap implementations.
public interface IDistributedCache
{
byte[] Get(string key);
Task<byte[]> GetAsync(string key, CancellationToken token = default);
void Set(string key, byte[] value, DistributedCacheEntryOptions options);
void Remove(string key);
void Refresh(string key);
}It Stores Bytes
Notice the cache stores byte[]. To cache strings or objects you serialize them first. Handy string extension methods exist for the common case.
using Microsoft.Extensions.Caching.Distributed;
await cache.SetStringAsync("greeting", "Hello, world");
string value = await cache.GetStringAsync("greeting");Injecting The Cache
Request IDistributedCache through constructor injection like any service.
public class WeatherService
{
private readonly IDistributedCache _cache;
public WeatherService(IDistributedCache cache)
{
_cache = cache;
}
}Reading From The Cache
GetStringAsync returns null when the key is absent or expired. Always handle the miss case.
string cached = await _cache.GetStringAsync("forecast:istanbul");
if (cached is null)
{
// cache miss: load from source
}Writing To The Cache
SetStringAsync stores a value with optional expiration options (covered in a later lesson).
await _cache.SetStringAsync(
"forecast:istanbul",
"22C sunny",
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});Removing And Refreshing
RemoveAsync evicts a key (for example when the underlying data changes). RefreshAsync resets a sliding expiration without changing the value.
await _cache.RemoveAsync("forecast:istanbul");
await _cache.RefreshAsync("session:abc123");The In-Memory Implementation
For development or tests, register the in-memory distributed cache. It implements the same interface, so your code is identical, but data is not actually shared across processes.
builder.Services.AddDistributedMemoryCache();Provider-Agnostic Code
Because you depend only on IDistributedCache, switching from the in-memory provider to Redis (or SQL Server) is a one-line registration change with no code changes in your services.
Key Naming Conventions
Use structured, namespaced keys like entity:id:field (e.g. user:42:profile). Clear conventions prevent collisions and make cache invalidation predictable.
string key = $"user:{userId}:profile";When Not To Cache
Cache data that is read often and changes rarely. Highly volatile or user-specific sensitive data may not be a good fit, and stale data risks must always be weighed against performance gains.
Quick Check
Test the IDistributedCache abstraction.
Recap
IDistributedCache abstracts an external, shared cache so every app instance sees the same data. It stores byte[], with GetStringAsync/SetStringAsync for strings, plus RemoveAsync and RefreshAsync. Depending on the interface keeps code provider-agnostic, switchable between AddDistributedMemoryCache and Redis with one line. Use clear namespaced keys.
Frequently asked questions
Is the “IDistributedCache Abstraction” lesson free?
Yes — the full text of “IDistributedCache Abstraction” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “IDistributedCache Abstraction”?
Cache data across multiple servers. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “IDistributedCache Abstraction” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- IDistributedCache Abstraction
- Connecting to Redis
- Cache Patterns and Expiration
- Caching Serialized Objects