LazyCache icon indicating copy to clipboard operation
LazyCache copied to clipboard

CachingService.TryGetValue returning wrong value

Open Coder3333 opened this issue 3 years ago • 2 comments

I expect CachingService.TryGetValue to return the value that I stored in the cache, but instead, it returns the Lazy that was used to generate the value. I would expect a call to GetValueFromLazy in this method to make sure the right object is returned. You will see this behavior if you use GetOrCreate to initially store the value, and then follow up with TryGetValue to read the value.

Also, because this re-uses T when calling CacheProvider.TryGetValue<T>, it never finds the value. You would need to use CacheProvider.TryGetValue to be able to fetch the value.

Here is the TryGetValue method from https://github.com/alastairtree/LazyCache/blob/master/LazyCache/CachingService.cs.

` public virtual bool TryGetValue<T>(string key, out T value) { ValidateKey(key);

        return CacheProvider.TryGetValue(key, out value);
    }

`

Coder3333 avatar Apr 27 '22 20:04 Coder3333

Yeah this looks like a bug to me - thanks for submitting it. It should return the correctly typed object and unwrap the lazy using GetValueFromLazy in the same way the GetOrAdd does.

I assume this test is also broken somehow - https://github.com/alastairtree/LazyCache/blob/master/LazyCache.UnitTests/CachingServiceMemoryCacheProviderTests.cs#L1155

Would you be willing to submit a PR for the broken test and a fix?

alastairtree avatar May 05 '22 11:05 alastairtree

I have raise a PR to try fix this, Please feel free to share your feedback.

phadtrapong avatar May 08 '22 03:05 phadtrapong