I need a way to map a non-generic type into a generic type for deserialization using IValueResolver
or IMemberValueResolver
I found this documentation that forwards to github tests.
The problem is that there are only mappings from open-generic type to non-generic type using IValueResolver
or from open-generic type to open-generic type. That way works as expected.
What I need to do is a mapping of a generic type to a non-generic type (that’s working) and vise versa for deserialiation.
My types are:
public sealed class Foo<T>
{
public T? Value { get; set; }
}
public sealed class SerializableFoo
{
public string? TypeAQN { get; set; }
public string? Data { get; set; }
}
I tried to create a mapping:
// Working
this.CreateMap(typeof(Foo<>), typeof(SerializableFoo), MemberList.None)
.ForMember(nameof(SerializableFoo.TypeAQN), opt => opt.MapFrom(typeof(TypeAQNValueResolver<>)))
.ForMember(nameof(SerializableFoo.Data), opt => opt.MapFrom(typeof(DataValueResolver<>)));
// not working
this.CreateMap(typeof(SerializableFoo), typeof(Foo<>), MemberList.None)
.ForMember(nameof(Foo<object>.Value), opt => opt.MapFrom(typeof(SerializableToFooValueResolver<,,,>)));
private sealed class TypeAQNValueResolver<T> : IValueResolver<Foo<T>, SerializableFoo, string?>
{
public string? Resolve(Foo<T> source, SerializableFoo destination, string? destMember, ResolutionContext context) =>
typeof(T).AssemblyQualifiedName;
}
private sealed class DataValueResolver<T> : IValueResolver<Foo<T>, SerializableFoo, string?>
{
/// <inheritdoc />
public string? Resolve(Foo<T> source, SerializableFoo destination, string? destMember, ResolutionContext context) =>
source.Value?.ToString() ?? "<null>";
}
I tried to create a IValueResolve
using one, two, three and even 4 generics and every time the runtime gives me this exception:
The number of generic arguments provided doesn't equal the arity of the generic type definition.
Parameter name: instantiation
No matter how many generic paramerters I add.
How does a mapping from non-generic type to open-generic type using IValueResolver
work?