August 10 2024

dotnet add package Microsoft.Extensions.Caching.Memory
builder.Services.AddMemoryCache();
private readonly IMemoryCache _cacheService; public WeatherForecastController(IMemoryCache cacheService) { _cacheService = cacheService; }
[HttpGet(Name = "GetWeatherForecast")] public List<WeatherForecast> Get() { if (!_cacheService.TryGetValue("MyCacheKey", out List<WeatherForecast> weathersFromCache)) { var weathers = Enumerable.Range(1, 300).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToList(); _cacheService.Set<List<WeatherForecast>>("MyCacheKey", weathers); return weathers; } return weathersFromCache; }
var cacheEntryOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) // Cache for 30 minutes }; _cacheService.Set<List<WeatherForecast>>("MyCacheKey", weathers, cacheEntryOptions);
var cacheEntryOptions = new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(30) // Cache for 30 minutes }; _cacheService.Set<List<WeatherForecast>>("MyCacheKey", weathers, cacheEntryOptions);
var cacheEntryOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1), // Absolute expiration of 1 hour SlidingExpiration = TimeSpan.FromMinutes(30) // Sliding expiration of 30 minutes }; _cacheService.Set<List<WeatherForecast>>("MyCacheKey", weathers, cacheEntryOptions);
var cacheEntryOptions = new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60), // Expires in 60 minutes SlidingExpiration = TimeSpan.FromMinutes(15), // Reset expiration to 15 minutes if accessed Priority = CacheItemPriority.High, // High priority Size = 1024 // Size of the entry is 1024 units }; cacheEntryOptions.RegisterPostEvictionCallback( (key, value, reason, state) => { Console.WriteLine($"Cache item {key} was removed due to {reason}."); } ); _memoryCache.Set("MyCacheKey", myObject, cacheEntryOptions);
1. Design Patterns that Deliver
This isn’t just another design patterns book. Dive into real-world examples and practical solutions to real problems in real applications.Check out it here.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Join 18,000+ subscribers to improve your .NET Knowledge.
Subscribe to the TheCodeMan.net and be among the 18,000+ subscribers gaining practical tips and resources to enhance your .NET expertise.
Powered by EmailOctopus