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.71k stars 159 forks source link

Get doesn't call function delegate added with Add #159

Closed mtfarkas closed 3 years ago

mtfarkas commented 3 years ago

Describe the bug If I add a Func<T> factory function to cache via the Add method, then later want to retrieve the value it provides via Get, the returned value will be a Func<T> instead of a value of type T.

To Reproduce Add a Func<T> to cache via the Add method, then retrieve it immediately via the Get method.

Expected behavior The factory function is called and the resulting value is returned instead of the function itself.

Framework and Platform

Additional context N/A

jodydonetti commented 3 years ago

That's not a bug, you are using it wrong.

The signature for the Add method is this:

void Add<T>(string key, T item, MemoryCacheEntryOptions policy);

So by calling Add you are "adding an item to the cache" and not "specifying a factory to be used with a cache key for later retrieval".

So basically while you think you are specifying the factory for later use, you are really adding the factory itself (a lambda) to the cache as the item: then when, later on, you ask for the item in the cache it will give you back that item, which is the lambda itself.

Hope this helps.

ps: @alastairtree if I've said something wrong please correct me.

mtfarkas commented 3 years ago

You're entirely right, but for some reason the IntelliSense in Visual Studio shows an overload that does take a Func as a second argument, I can't reproduce this outside of this one project. Thanks for pointing out and sorry for bothering.

jodydonetti commented 3 years ago

No worries! Even though this is not my lib now I'm curious about the situation you're talking about, will try to reproduce it out of curiosity. Best.

alastairtree commented 3 years ago

All good then, use the GetOrAdd method for the behaviour you are seeking.