Files
Umbraco-CMS/src/Umbraco.Core/Cache/ValueEditorCache.cs

63 lines
2.5 KiB
C#
Raw Normal View History

2021-08-23 14:28:44 +02:00
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
2021-08-23 14:28:44 +02:00
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.PropertyEditors;
namespace Umbraco.Cms.Core.Cache
{
public class ValueEditorCache : IValueEditorCache
2021-08-23 14:28:44 +02:00
{
2021-08-24 10:38:38 +02:00
private readonly Dictionary<string, Dictionary<int, IDataValueEditor>> _valueEditorCache;
private readonly object _dictionaryLocker;
public ValueEditorCache()
{
_valueEditorCache = new Dictionary<string, Dictionary<int, IDataValueEditor>>();
_dictionaryLocker = new object();
}
2021-08-23 14:28:44 +02:00
public IDataValueEditor GetValueEditor(IDataEditor editor, IDataType dataType)
{
2021-08-24 10:38:38 +02:00
// Lock just in case multiple threads uses the cache at the same time.
lock (_dictionaryLocker)
2021-08-23 14:28:44 +02:00
{
2021-08-24 10:38:38 +02:00
// We try and get the dictionary based on the IDataEditor alias,
// this is here just in case a data type can have more than one value data editor.
// If this is not the case this could be simplified quite a bit, by just using the inner dictionary only.
IDataValueEditor? valueEditor;
if (_valueEditorCache.TryGetValue(editor.Alias, out Dictionary<int, IDataValueEditor>? dataEditorCache))
2021-08-23 14:28:44 +02:00
{
2021-08-24 10:38:38 +02:00
if (dataEditorCache.TryGetValue(dataType.Id, out valueEditor))
{
return valueEditor;
}
valueEditor = editor.GetValueEditor(dataType.Configuration);
dataEditorCache[dataType.Id] = valueEditor;
2021-08-23 14:28:44 +02:00
return valueEditor;
}
valueEditor = editor.GetValueEditor(dataType.Configuration);
2021-08-24 10:38:38 +02:00
_valueEditorCache[editor.Alias] = new Dictionary<int, IDataValueEditor> { [dataType.Id] = valueEditor };
2021-08-23 14:28:44 +02:00
return valueEditor;
}
}
public void ClearCache(IEnumerable<int> dataTypeIds)
2021-08-23 14:28:44 +02:00
{
2021-08-24 10:38:38 +02:00
lock (_dictionaryLocker)
2021-08-23 14:28:44 +02:00
{
2021-08-24 10:38:38 +02:00
// If a datatype is saved or deleted we have to clear any value editors based on their ID from the cache,
// since it could mean that their configuration has changed.
foreach (var id in dataTypeIds)
2021-08-23 14:28:44 +02:00
{
2021-08-24 10:38:38 +02:00
foreach (Dictionary<int, IDataValueEditor> editors in _valueEditorCache.Values)
{
editors.Remove(id);
}
2021-08-23 14:28:44 +02:00
}
}
}
}
}