Dynamic Cache Key in GetOrSetAsync Factory #563
Answered
by
jodydonetti
ShaumCAtCpdi
asked this question in
Q&A
-
|
Hello! I was wondering is there a way to change the CacheKey that will be set as part of the factory of GetOrSetAsync? I can do it outside of the factory but I was more curious if there was a way to do so within the factory with the ctx object Example is this: public async Task<Result<ObjectDto>> GetObjectByIdentifier(string objectIdentifier, CancellationToken cts = default)
{
return await _cache.GetOrSetAsync<Result<ObjectDto>>(
CacheKeys.Object.ByObjectIdentifier(objectIdentifier),
async (ctx, ct) =>
{
// Call Repository Method
var objectResult = await _objectRepository.GetObjectByIdentifier(objectIdentifier, ct);
// Check if Repository Method is a Success
if (!object.Success)
return ctx.Fail(objectResult.ErrorCode);
// Change the cache key here to be By ObjectId instead of ObjectIdentifier
// i.e. CacheKeys.Object.ByObjectId(objectResult.Id)
// Return Result
return objectResult;
},
tags: [CacheKeys.Object.Tag],
failSafeDefaultValue: Result<ObjectDto>.Fail(ErrorMessages.Codes.Server.InternalError),
token: cts
);
} |
Beta Was this translation helpful? Give feedback.
Answered by
jodydonetti
Dec 2, 2025
Replies: 1 comment 2 replies
-
|
Hi @ShaumCAtCpdi Hope this helps. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
ShaumCAtCpdi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @ShaumCAtCpdi
no, there's no way to do it: the cache key is the fundamental piece of information that uniquely identify each entry in the cache, and computing it (or changing it) mid-flight cannot possibly work.
Hope this helps.