Junior MVC

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:

More from ASP.NET Core MVC Tutorial

All questions for this course