Last active
November 15, 2018 03:06
-
-
Save FoxCouncil/155696b4aac0fe8b4c9dd3b706ef7ebf to your computer and use it in GitHub Desktop.
ASP.NET Core 2.1 - Controller Caching Anonymous Method Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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