first we will define a MemoryCache and AsyncLock
private static readonly MemoryCache cache = MemoryCache.Default; private static readonly AsyncLock myAsyncLock = new AsyncLock();
second we will write the logic to utilize the cache from MemoryCache.
const string CacheKey = "MyCacheKey"; var myCacheObjects = cache.Get(CacheKey) as Cache Object type; if (myCacheObjects == null) { using (await myAsyncLock.LockAsync()) { //your logic here to load the cache objects
cache.Set(CacheKey, titles, new CacheItemPolicy()
{ AbsoluteExpiration = DateTimeOffset.Now.AddHours(12) }); } } return myCacheObjects ;
if we have more objects to be cache in the project, then we will have code redudent issue. since cache logic need to copy everywhere. the maintainance will be an issue as well. since the logic had been copied everywhere
i copied the idea from this link after i google for a solution.
How to cache data in a MVC application
i just a modification so that it handle the async call on loading the data for caching..
public class MemoryCacheService : ICacheService { public async Task<T> GetOrSetAsync<T>(string cacheKey, Func<Task<T>> getItemCallback)
where T : class { T item = MemoryCache.Default.Get(cacheKey) as T; if (item == null) { item =await getItemCallback(); MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(12)); } return item; } } interface ICacheService { Task<T> GetOrSetAsync<T>(string cacheKey, Func<Task<T>> getItemCallback)
where T : class; }
how to use this caching service. please view the following snippet of code.
[Route("api/title")] public async Task<IList<Title>> GetMYTitles() { const string cacheKey = "WebApi-GetTitles"; MemoryCacheService memoryCacheService = new MemoryCacheService(); System.Func<Task<IList<Salution>>> myFunGetTitles =
async () => await GetTitlesAsync(); return await memoryCacheService.GetOrSetAsync<IList<Salution>>
(cacheKey, myFunGetTitles); } private async Task<IList<Title>> GetTitlesAsync() { string url = "salutations"; APIResult result = await InvokeAzureAPICall(url); IList<Salution> titles = (List<Title>)JsonConvert.DeserializeObject
(result.apiResponse, typeof(List<Title>)); return titles; }
if you like it, feel free to take it and your feed back will be greatly appreciated.
Happy programming
No comments:
Post a Comment