2025-08-28 18:46:55 +02:00

30 lines
1.1 KiB
C#

using Microsoft.Extensions.Caching.Memory;
namespace EnvelopeGenerator.Application.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}'.");
}