Output caching (new in .NET 8) β Server-side output reuse. Example: builder.Services.AddMemoryCache(); public class ProductService { private readonly IMemoryCache _cache; public ProductService(IMemoryCache cache) => _cache = cache; public IEnumerable<Product> GetProducts() { if (!_cache.TryGetValue("products", out IEnumerable<Product> products)) { products = FetchFromDatabase(); Follow : _cache.Set("products", products, TimeSpan.FromMinutes(5)); } return products; } } β Reduces DB load and speeds up response times. πΎ 2. What is In-Memory Caching?
In-memory caching stores data in the memory of the application server.
Itβs fast, but data is lost if the app restarts or scales across multiple servers.
Setup:
builder.Services.AddMemoryCache();
Usage:
_cache.Set("key", value, TimeSpan.FromMinutes(10));
var data = _cache.Get("key");
β Ideal for single-server apps or short-term caching (e.g., reference data, dropdown lists).
β Not suitable for load-balanced environments.
π 3. What is Distributed Caching?
Distributed caching stores data in an external cache server (e.g., Redis, SQL Server), so
all app instances share the same cache.
Setup:
builder.Services.AddStackExchangeRedisCache(options =>
Follow :
options.Configuration = "localhost:6379";
options.InstanceName = "MyApp_";
});
Usage:
public class CacheService
private readonly IDistributedCache _cache;
public CacheService(IDistributedCache cache) => _cache = cache;
public async Task<string> GetCachedDataAsync()
var data = await _cache.GetStringAsync("welcome");
if (data == null)
data = "Hello, from Redis!";
await _cache.SetStringAsync("welcome", data,
new DistributedCacheEntryOptions
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(10)
});
return data;
β Great for cloud, containerized, or multi-server setups.
π§ 4. How do you use Redis caching?
Redis is a fast, in-memory, key-value data store used for distributed caching.
Follow :
Steps: