| | | 1 | | using Microsoft.Extensions.Options; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Common.Serialization; |
| | | 4 | | |
| | | 5 | | /// <inheritdoc /> |
| | | 6 | | public class SerializationTypeRegistry : ISerializationTypeRegistry |
| | | 7 | | { |
| | 10165 | 8 | | private readonly Dictionary<string, Type> _aliasTypeDictionary = new(StringComparer.OrdinalIgnoreCase); |
| | 10165 | 9 | | private readonly Dictionary<Type, string> _typeAliasDictionary = new(); |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Creates a default registry. |
| | | 13 | | /// </summary> |
| | | 14 | | public static ISerializationTypeRegistry CreateDefault() |
| | | 15 | | { |
| | 10162 | 16 | | return new SerializationTypeRegistry(Microsoft.Extensions.Options.Options.Create(new SerializationTypeOptions()) |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance of the <see cref="SerializationTypeRegistry"/> class. |
| | | 21 | | /// </summary> |
| | 10165 | 22 | | public SerializationTypeRegistry(IOptions<SerializationTypeOptions> options) |
| | | 23 | | { |
| | 529390 | 24 | | foreach (var entry in options.Value.AliasTypeDictionary) |
| | 254530 | 25 | | RegisterTypeName(entry.Value, entry.Key); |
| | | 26 | | |
| | 509012 | 27 | | foreach (var entry in options.Value.TypeAliasDictionary) |
| | 244341 | 28 | | RegisterType(entry.Key, entry.Value); |
| | 10165 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <inheritdoc /> |
| | | 32 | | public void RegisterType(Type type, string alias) |
| | | 33 | | { |
| | 244341 | 34 | | _typeAliasDictionary[type] = alias; |
| | 244341 | 35 | | RegisterTypeName(type, alias); |
| | 244341 | 36 | | } |
| | | 37 | | |
| | | 38 | | /// <inheritdoc /> |
| | 28043 | 39 | | public bool TryGetAlias(Type type, out string alias) => _typeAliasDictionary.TryGetValue(type, out alias!); |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | 10151 | 42 | | public bool TryGetType(string alias, out Type type) => _aliasTypeDictionary.TryGetValue(alias, out type!); |
| | | 43 | | |
| | | 44 | | /// <inheritdoc /> |
| | 0 | 45 | | public IEnumerable<Type> ListTypes() => _aliasTypeDictionary.Values.Distinct(); |
| | | 46 | | |
| | | 47 | | private void RegisterTypeName(Type type, string alias) |
| | | 48 | | { |
| | 498871 | 49 | | _aliasTypeDictionary[alias] = type; |
| | | 50 | | |
| | 498871 | 51 | | if (type.IsPrimitive || type.IsValueType && Nullable.GetUnderlyingType(type) == null) |
| | | 52 | | { |
| | 254143 | 53 | | var nullableType = typeof(Nullable<>).MakeGenericType(type); |
| | 254143 | 54 | | _aliasTypeDictionary[$"{alias}?"] = nullableType; |
| | | 55 | | |
| | 254143 | 56 | | if (_typeAliasDictionary.ContainsKey(type)) |
| | 121986 | 57 | | _typeAliasDictionary[nullableType] = $"{alias}?"; |
| | | 58 | | } |
| | 498871 | 59 | | } |
| | | 60 | | } |