Skip to content

Commit

Permalink
Try a custom SerializationBinder so that moving namespaces doesn't co…
Browse files Browse the repository at this point in the history
…mpletely break filters
  • Loading branch information
da3dsoul committed Oct 2, 2023
1 parent e608431 commit d270c27
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, System.Global
{
MissingMemberHandling = MissingMemberHandling.Ignore,
TypeNameHandling = TypeNameHandling.Objects,
SerializationBinder = new SimpleNameSerializationBinder(),
Error = (_, args) =>
{
LogManager.GetCurrentClassLogger().Error(args.ErrorContext.Error);
Expand Down Expand Up @@ -60,7 +61,8 @@ public override object ConvertTo(ITypeDescriptorContext context, System.Globaliz
return JsonConvert.SerializeObject(value, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore,
TypeNameHandling = TypeNameHandling.Objects
TypeNameHandling = TypeNameHandling.Objects,
SerializationBinder = new SimpleNameSerializationBinder(),
});
}

Expand Down
33 changes: 33 additions & 0 deletions Shoko.Server/Databases/NHIbernate/SimpleNameSerializationBinder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using System.Linq;
using Newtonsoft.Json.Serialization;
using NLog;

namespace Shoko.Server.Databases.NHIbernate;

public class SimpleNameSerializationBinder : DefaultSerializationBinder
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly Type _baseType;

public SimpleNameSerializationBinder(Type baseType = null)
{
_baseType = baseType;
}

public override void BindToName(
Type serializedType, out string assemblyName, out string typeName)
{
assemblyName = null;
typeName = serializedType.Name;
}

public override Type BindToType(string assemblyName, string typeName)
{
var name = typeName.Split('.').LastOrDefault();
var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
.Where(a => a.Name.Equals(name) && (_baseType == null || _baseType.IsAssignableFrom(a))).ToArray();
if (types.Length > 1) _logger.Warn($"SimpleNameSerializationBinder found multiple types that match {name}");
return types.FirstOrDefault();
}
}

0 comments on commit d270c27

Please sign in to comment.