One thing that ASP.Net Core really got right was caching.
<a href="https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory">IMemoryCache</a> is a caching implementation that does just what I want. I love it. I take it everywhere. I've introduced it to my family.
To make usage of the
IMemoryCacheeven 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:
Usage looks like this:
This helper allows the consumer to provide three things:
keykey for the item to be cached with
itemGetterAsyncwhich is the method that is used to retrieve a new value if an item cannot be found in the cache
timeToCachewhich is the period of time that an item should be cached
If 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.
Go on, ask me how I know.
This is a simple, clear and helpful API which makes interacting with
IMemoryCache even more lovely than it was. Peep it y'all.