- ASP.NET Core MVC
- ASP.NET Core logging with Serilog
- ASP.NET Core managed config
- ASP.NET Core MVC with /api/-area
- ASP.NET Core API versioning
- ASP.NET Core API with Swagger UI
- ASP.NET Core EF in separate project
- ASP.NET Core AutoMapper
- ASP.NET Core response cache
- ASP.NET Core memory cache
- ASP.NET Core TypeScript
Response cache is fine for simpler operations, but sometimes you need more fine grained control. System.Runtime.Caching.MemoryCache has builtin support for in-memory cache with expiry.
Install
1 |
Install-Package System.Runtime.Caching |
Implement
To register as a service add this to Startup.cs ConfigureServices:
1 |
services.AddMemoryCache(); |
Use
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class HomeController : Controller { private readonly IMemoryCache _cache; public HomeController(IMemoryCache memoryCache) { _cache = memoryCache; } [HttpGet] public string CurrentTime() { var cacheEntry = _cache.GetOrCreate("CurrentTime", entry => { entry.SlidingExpiration = TimeSpan.FromSeconds(10); return DateTime.Now.ToString(); }); return cacheEntry; } } |
A colleague requested a more complex scenario where we need the cache to update exactly every 1 minute, since numbers from all requests to that particular API should be approximately in sync.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[HttpGet] public string CurrentTime() { var cacheEntry = _cache.GetOrCreate("CurrentTime", entry => { // Calculate next whole minute var now = DateTimeOffset.Now.ToUnixTimeSeconds(); var expires = now + 60 - (now % 60); entry.AbsoluteExpiration = DateTimeOffset.FromUnixTimeSeconds(expires); return DateTime.Now.ToString(); }); return cacheEntry; } |