Skip to content

Commit

Permalink
Automatically detect attribute for derived type and prevent interface…
Browse files Browse the repository at this point in the history
… proxy creation (Fixes MassTransit#4313
  • Loading branch information
phatboyg committed Apr 19, 2023
1 parent b96b0db commit f0b0029
Showing 1 changed file with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public override bool CanConvert(Type typeToConvert)
if (_openTypeFactory.TryGetValue(typeInfo, out _))
return true;

if (typeToConvert.IsInterfaceOrConcreteClass() && MessageTypeCache.IsValidMessageType(typeToConvert) && !typeToConvert.IsValueTypeOrObject())
if (IsConvertibleInterfaceType(typeToConvert))
return true;

return false;
Expand Down Expand Up @@ -157,14 +157,38 @@ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializer
}
}

if (typeToConvert.IsInterfaceOrConcreteClass() && MessageTypeCache.IsValidMessageType(typeToConvert) && !typeToConvert.IsValueTypeOrObject())
if (IsConvertibleInterfaceType(typeToConvert))
{
return (JsonConverter)Activator.CreateInstance(
typeof(InterfaceJsonConverter<,>).MakeGenericType(typeToConvert, TypeMetadataCache.GetImplementationType(typeToConvert)));
}

throw new MassTransitException($"Unsupported type for json serialization {TypeCache.GetShortName(typeInfo)}");
}

static bool IsConvertibleInterfaceType(Type typeToConvert)
{
if (!typeToConvert.IsInterfaceOrConcreteClass())
return false;

if (!MessageTypeCache.IsValidMessageType(typeToConvert))
return false;

if (typeToConvert.IsValueTypeOrObject())
return false;

foreach (var attribute in typeToConvert.GetCustomAttributes())
{
switch (attribute.GetType().Name)
{
case "JsonDerivedTypeAttribute":
case "JsonPolymorphicAttribute":
return false;
}
}

return true;
}
}


Expand Down

0 comments on commit f0b0029

Please sign in to comment.