Created
July 12, 2021 15:19
-
-
Save DrewQuick/71d121095d475fca89c5473d7d1c3d18 to your computer and use it in GitHub Desktop.
Cache Eval
This file contains 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
// Implementation | |
private const int DEFAULT_RETENTION = 60; | |
public static T Eval<T>(this IMemoryCache cache, string key, Func<T> expression) | |
=> Eval(cache, key, DEFAULT_RETENTION, expression); | |
public static T Eval<T>(this IMemoryCache cache, string key, int retentionMinutes, Func<T> expression) | |
{ | |
T val; | |
if (!cache.TryGetValue<T>(key, out val)) | |
{ | |
val = expression(); | |
cache.Set(key, val, new TimeSpan(retentionMinutes / 60, retentionMinutes % 60, 0)); | |
} | |
return val; | |
} | |
// Usage | |
public IActionResult GetMyModel(int Id) | |
{ | |
var vm = _cache.Eval<MyModel>("myModelCacheKey", () => { | |
return _db.Query<MyModel>("SELECT * FROM dbo.MyModel WHERE Id = @Id", new { Id }); | |
}); | |
return Json(vm); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment