alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.72k stars 159 forks source link

Policy should be supplied when refreshing the cache due to type mismatch #149

Open ajbeaven opened 3 years ago

ajbeaven commented 3 years ago

I have been struggling to get LazyCache to behave when setting a SizeLimit in the underlying MemoryCache. Intermittently it seemed, it would throw the following exception despite me supplying a size with the cache entry:

InvalidOperationException: Cache entry must specify a value for Size when SizeLimit is set.

Looking at the code, it appears in the situation where you have a type mis-match, the cache is refreshed however the supplied policy is not passed through which was causing the exception to be thrown.

I'm somewhat surprised no one has faced this before so I'm 70% sure I'm doing something wrong here. Consider this a very tentative PR ;)

alastairtree commented 3 years ago

Thanks for this - looks like a genuine bug! Any chance you could add a unit tests that reproduces the issue so we don't make this mistake again?

ajbeaven commented 3 years ago

I've added a couple of tests that should do the job. It doesn't test that associated extension methods use IAppCache.GetOrAdd<T>() (the method I cover in my tests) internally, but I assume this is covered elsewhere.

It'd look cleaner to use the GetOrAdd<T>() extension method that takes a TimeSpan, but it's probably safer to test this way. Let me know if you prefer aesthetics though, and I'll change it :)