Files
telegram-bot/Core/SerializationBinder.cs
T

50 lines
1.4 KiB
C#
Raw Normal View History

2024-05-29 00:19:30 +03:00
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Kruzya.TelegramBot.Core
{
public class SerializationBinder : ISerializationBinder
{
protected IDictionary<string, Type> _allowedTypes = new Dictionary<string, Type>();
public void RegisterAllowedType(string name, Type type)
{
if (_allowedTypes.ContainsKey(name))
{
throw new ArgumentException($"{name} is already registered", "name");
}
foreach (var knownType in _allowedTypes.Values)
{
if (type != knownType)
{
continue;
}
throw new ArgumentException($"{type.FullName} is already known type", "type");
}
_allowedTypes.Add(name, type);
}
public void RegisterAllowedType<T>(string name) where T : class
{
RegisterAllowedType(name, typeof(T));
}
public void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
assemblyName = null;
typeName = _allowedTypes.Where(x => x.Value == serializedType)
.FirstOrDefault().Key;
}
public Type BindToType(string assemblyName, string typeName)
{
return _allowedTypes[typeName];
}
}
}