Skip to content

Instantly share code, notes, and snippets.

@DrewQuick
Created July 12, 2021 15:19
Show Gist options
  • Save DrewQuick/71d121095d475fca89c5473d7d1c3d18 to your computer and use it in GitHub Desktop.
Save DrewQuick/71d121095d475fca89c5473d7d1c3d18 to your computer and use it in GitHub Desktop.
Cache Eval
// 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