To use an in memory cache in your ASP.NET application, add the following dependencies to your project.json
file:
"Microsoft.Extensions.Caching.Memory": "1.0.0-rc2-final",
add the cache service (from Microsoft.Extensions.Caching.Memory) to ConfigureServices method in Startup class
services.AddMemoryCache();
To add items to the cache in our application, we will use IMemoryCache
which can be injected to any class (for example Controller) as shown below.
private IMemoryCache _memoryCache;
public HomeController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
Get will return the value if it exists, but otherwise returns null
.
// try to get the cached item; null if not found
// greeting = _memoryCache.Get(cacheKey) as string;
// alternately, TryGet returns true if the cache entry was found
if(!_memoryCache.TryGetValue(cacheKey, out greeting))
Use the Set method to write to the cache. Set accepts the key to use to look up the value, the value to be cached, and a set of MemoryCacheEntryOptions
. The MemoryCacheEntryOptions
allow you to specify absolute or sliding time-based cache expiration, caching priority, callbacks, and dependencies. One of the sample below-
_memoryCache.Set(cacheKey, greeting,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(1)));