Closed felipedrumond closed 7 years ago
I managed to do it, and I'll write a piece of code for others just as an example
-- creates my policy
CacheItemPolicy policyWithExpirationCallBack = new CacheItemPolicy
{
AbsoluteExpiration = DateTime.Now.AddMinutes(1),
RemovedCallback = OnCacheExpired
};
-- gets an existing list of banners. If that list does not exist yet, add one with my policy
List<Banner> banners = cache.GetOrAdd(
"yourCacheName",
() =>
{
return _bannerRepository.ReadAll();
},
policyWithExpirationCallBack);
return banners;
-- method to be called when my cache expires
private void OnCacheExpired(CacheEntryRemovedArguments arguments)
{
// if you need the last version of your cached data, you can get it from arguments.CacheItem.Value
var lastVersionOfBanners = (List<Banner>)arguments.CacheItem.Value;
}
Thanks for this, I have updated the docs with an example based on yours: https://github.com/alastairtree/LazyCache/wiki/1.0-LazyCache-API-documentation#custom-cache-policies
Is there any way to configure an event to be run when the cache expires?
My scenario is the following: I have a web api that serves a list of banners. I want to increase their 'views' property every time I display every banner. Instead of updating the repository every time, it's better to update that property in the cached list and update the repository only when the cache expires.