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

Question/Proposal on the limit of Cache keying to strings vs. "TKey" #182

Open qwazwak opened 1 year ago

qwazwak commented 1 year ago

[Use the Thumbs Up reaction to vote for this feature, and please avoid adding comments like "+1" as they create noise for others watching the issue.]

Is your feature request related to a problem? Please describe. I haven't seen any discussion here on why this is done, nor on doing it. I will admit functionally limiting cache keys to a single string does not make it anything I am aware of impossible, but just problematic. Mainly having to parse (both ways) "composite" keys for value construction/fetching. The advantage would be that custom types/records could be easily used and make the factory methods far simpler.

Describe the solution you'd like The current implementation of CachingService would have it's string keys replaced with TKey, and the class declaration would be along the lines of public class CachingService<TKey> : IAppCache<TKey> where TKey : notnull

There is also the option of allowing use of custom Hash functions, either by a delegate similar to DefaultCachePolicy and (non static) DefaultCacheProvider or by inheritance via a virtual method.

The current functionality/compatibility could be maintained by (after CachingService is changed to CachingService) adding a derived class CachingService, shown below, implementing CachingService and overriding ValidateKey(string key) to provide the functionality of rejecting empty/whitespace keys.

    public class CachingService : CachingService<string>
    {
        /*
         * Constructors simply call the equivelent base constructor
         */

        protected override void ValidateKey(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw key == null ? new ArgumentNullException(nameof(key)) : new ArgumentOutOfRangeException(nameof(key), "Cache keys cannot be empty or whitespace");
        }
    }

Additional context As mentioned in the proposed solution, compatibility/functionality would be maintained.