Skip to content

Instantly share code, notes, and snippets.

@FoxCouncil
Last active November 15, 2018 03:06
Show Gist options
  • Save FoxCouncil/155696b4aac0fe8b4c9dd3b706ef7ebf to your computer and use it in GitHub Desktop.
Save FoxCouncil/155696b4aac0fe8b4c9dd3b706ef7ebf to your computer and use it in GitHub Desktop.
ASP.NET Core 2.1 - Controller Caching Anonymous Method Function
// Copyright (c) Fox Council - License: MIT
/*
* Usage Example:
* [HttpGet]
* public async Task<IActionResult> All()
* {
* return await this.Cached(TimeSpan.FromMinutes(15), async () => {
* await _stuff.SomeLongTask();
* return await _stuff.GetStuff();
* });
* }
*/
namespace FoxCouncil.Gist.AspNetCore
{
public static class Extensions
{
public static async Task<T> Cached<T>(this Controller controller, TimeSpan cacheLength, Func<Task<T>> fetchMethod)
{
var cacheSystem = controller.HttpContext.RequestServices.GetService<IMemoryCache>();
var cacheKey = controller.Request.Path.ToString();
if (cacheSystem.TryGetValue(cacheKey, out T result))
{
return result;
}
return cacheSystem.Set(cacheKey, await fetchMethod(), new MemoryCacheEntryOptions().SetSlidingExpiration(cacheLength));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment