{
"$type": "site.standard.document",
"canonicalUrl": "https://johnnyreilly.com/posts/dotnet-imemorycache-getorcreatefortimespanasync",
"description": "IMemoryCache is a tremendous caching mechanism for .NET. This post demonstrates how to write a helper to allow you to get or create an item for a given TimeSpan.",
"path": "/posts/dotnet-imemorycache-getorcreatefortimespanasync",
"publishedAt": "2018-12-10T00:00:00.000Z",
"site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
"tags": [
"asp.net"
],
"textContent": "One thing that ASP.Net Core really got right was caching. IMemoryCache is a caching implementation that does just what I want.\n\n\n\nTimeSpan, TimeSpan Expiration Y'all\n\nTo make usage of the IMemoryCache _even_ more lovely I've written an extension method. I follow pretty much one cache strategy: SetAbsoluteExpiration and I just vary the expiration by an amount of time. This extension method implements that in a simple way; I call it GetOrCreateForTimeSpanAsync - catchy right? It looks like this:\n\nUsage looks like this:\n\nWhere _cache is an instance of IMemoryCache that can be dependency injected into your class. This helper allows the consumer to provide three things:\n\n- The key key for the item to be cached with\n- A itemGetterAsync which is the method that is used to retrieve a new value if an item cannot be found in the cache\n- A timeToCache which is the period of time that an item should be cached\n\nIf an item can't be looked up by the itemGetterAsync then _nothing_ will be cached and a the default value of the expected type will be returned. This is important because lookups can fail, and there's nothing worse than a lookup failing and you caching null as a result.\n\nGo on, ask me how I know.\n\nThis is a simple, clear and helpful API which makes interacting with IMemoryCache even more lovely than it was.",
"title": "IMemoryCache and GetOrCreateForTimeSpanAsync"
}