using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; namespace Kruzya.TelegramBot.Core { public class SerializationBinder : ISerializationBinder { protected IDictionary _allowedTypes = new Dictionary(); 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(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]; } } }