如何使用 AutoMapper 创建从开放泛型到简单泛型的自定义类型转换器?

问题描述 投票:0回答:0

我有一个从函数式程序语言实现选项 monad 的类。实现非常简单:

public class Maybe<T> : IMaybe<T>
{
  public T Value { get; set; } = default!;
  public bool IsDefined { get; set; }
  // Other methods that aren't relevant
}

我想定义一个自动映射器配置,以便当一个

Maybe<T>
被映射到一个
T
时,返回
Value
Maybe<T>
属性。

文档只有映射的两边都是开放泛型的情况,但是按照这种模式我定义了一个自定义转换器:

public class MaybeToUnwrappedConverter<TSource> : ITypeConverter<Maybe<TSource>, TSource>
{
  public TSource Convert(Maybe<TSource> source, TSource destination, ResolutionContext context) => source.Value;
}

并为其添加了个人资料:

CreateMap(typeof(Maybe<>), typeof(object))
  .ConvertUsing(typeof(MaybeToUnwrappedConverter<>));

但是在应用程序启动时

Expression of type 'System.Object' cannot be used for assignment to type ResourceAllocation
ResourceAllocation
是项目中的 DTO 之一)。我假设发生这种情况是因为 AutoMapper 的启动验证使用的是
CreateMap
中定义的类型,而不是从转换器返回的运行时类型。

有没有办法配置 AutoMapper 来完成这项工作?

c# automapper
© www.soinside.com 2019 - 2024. All rights reserved.