I have this following code block, which is receving a sessionId and need to return the related userId.
private static async Task<string> AddOrGetExisting(string sessionId, Func<Task<Tuple<string, DateTime>>> factory)
{
var newValue = new Lazy<Task<Tuple<string, DateTime>>>(factory);
var oldValue = _cache.AddOrGetExisting(sessionId, newValue, new CacheItemPolicy() { AbsoluteExpiration = (await newValue.Value).Item2 } ) as Lazy<Task<Tuple<string, DateTime>>>;
try
{
return (await (oldValue ?? newValue).Value).Item1;
}
catch
{
_cache.Remove(sessionId);
throw;
}
}
Whenever I store a session, i want the cache to store it only until it expires.
The tuple contains the (string)UserId
and (DateTime)ExpirationDate
.
The problem with what I wrote is that im invoking the factory all the time which fetches the data from the datebase which is kinda ruin the whole idea of cache.
How can I access the value only after/if it was retreived?