Developer 02 6126fce24d Refactor MemoryCacheExtensions and HistoryController
Updated MemoryCacheExtensions to accept more flexible parameters in GetEnumAsDictionary and improved the merging logic for ignored values. Simplified HistoryController by removing the logger dependency and adjusted GetReferenceTypes to include a key parameter for cache retrieval.
2025-05-11 15:19:37 +02:00

30 lines
1.1 KiB
C#

using Microsoft.Extensions.Caching.Memory;
namespace EnvelopeGenerator.Extensions;
public static class MemoryCacheExtensions
{
private static readonly Guid BaseId = Guid.NewGuid();
public static IDictionary<string, int> GetEnumAsDictionary<TEnum>(this IMemoryCache memoryCache, string key = "", params object[] ignores)
where TEnum : Enum
=> memoryCache.GetOrCreate(BaseId + typeof(TEnum).FullName + key, _ =>
{
var mergedIgnores = new List<TEnum>();
foreach (var ignore in ignores)
{
if (ignore is IEnumerable<TEnum> ignoreList)
mergedIgnores.AddRange(ignoreList);
else if (ignore is TEnum ignoreVal)
mergedIgnores.Add(ignoreVal);
}
return Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(e => !mergedIgnores.Contains(e))
.ToDictionary(e => e.ToString(), e => Convert.ToInt32(e));
})
?? throw new InvalidOperationException($"Failed to cache or retrieve enum dictionary for type '{typeof(TEnum).FullName}'.");
}