RicoSuter / Namotion.Reflection

.NET library with advanced reflection APIs.
MIT License
212 stars 44 forks source link

ContextualFieldInfo throws with generic types #143

Closed ms0815user closed 3 months ago

ms0815user commented 8 months ago

I am using NJsonSchema (11.0.0) with Namotion.Reflection (3.1.1) and encountered a problem during schema generation. Below is a shorted example of my usecase.

public class Hashid
{
    protected long _id;

    ...
}

public sealed class Hashid<T> : Hashid
    where T : EntityBase
{
    ...
}

public Request
{
    public Hashid RegionId { get; set; } // works

    public Hashid<Domain.Entities.User> UserId { get; set; } // fails
}

During the schema generation and exploration of the Request the following exception is thrown:

System.InvalidOperationException: This operation is only valid on generic types.
   at System.RuntimeType.GetGenericTypeDefinition()
   at Namotion.Reflection.ContextualType.<get_Fields>b__36_0(FieldInfo field)
   at System.Linq.Enumerable.SelectArrayIterator`2.Fill(ReadOnlySpan`1 source, Span`1 destination, Func`2 func)
   at System.Linq.Enumerable.SelectArrayIterator`2.ToArray()
   at Namotion.Reflection.ContextualType.get_Fields()
   at NJsonSchema.NewtonsoftJson.Generation.NewtonsoftJsonReflectionService.GenerateProperties(JsonSchema schema, ContextualType contextualType, NewtonsoftJsonSchemaGeneratorSettings settings, JsonSchemaGenerator schemaGenerator, JsonSchemaResolver schemaResolver)
...

This happens because in the Fields property of the ContextualType class the TypeInfo is generic but the DeclaringType of the field is not.

grafik

This could be related to #139.

I currently resolved this issue for me by not having the Hashid<T> inherit from Hashid and copy part of the logic.