I have a CacheService
that uses GetOrCreateAsync
to create cache based on a key. I am caching a photograph entity, which has a byte[]
property.
This caches fine and is retrieved as expected. However if the photograph entity is updated, the cache still retains the old entity as you would expect because it has not expired, how can I force an update to the cache upon save of this entity? Do I remove the existing cached entity and re-add the updated one?
Example of my FromCacheAsync
method in my CacheService
public async Task<T> FromCacheAsync<T>(string entityName, int clientId, Func<Task<T>> function)
{
string cacheKey = GetClientCacheKey(entityName, clientId, function);
if (!_cache.TryGetValue(cacheKey, out T entry))
{
async Task<T> factory(ICacheEntry cacheEntry)
{
return await function();
}
return await _cache.GetOrCreateAsync(cacheKey, factory);
}
return entry;
}
This is an example of using the caching.
var existingPhotograph = await _cacheService.FromCacheAsync(nameof(_context.Photograph), clientId, async () =>
await _photographRepository.GetByStaffIdAsync(staff.StaffId));
You need to invalidate the cache key, when the entity changes.
That may be a bit tricky, if you directly operate on the DbContext. But since you are using repository pattern, that`s easier to do.
It boils down to inject the
IMemoryCache
into your repository and invalidate it when a picture is updated.Using with Decorator pattern
The catch is, the built-in DI/IoC container doesn't support decorator registrations, so you'll have to make it yourself via factory pattern or use a 3rd party IoC container which supports it.
It's per se not "bad" to use new within the composition root (where you configure your DI/IoC container), but with 3rd party IoC container its just more convenient.
Of course you can also register
PhotographRepository
with the IoC container and have it resolved. But that would also allow you to injectPhotographRepository
into your services whereas the above prevents it, because only theIPhotographRepository
interface is registered.