首页 > 解决方案 > 映射容器使用 AutoMapper 到 T

问题描述

我的问题与此处提出的问题非常相似,但我无法根据提供的答案找到解决方案。我一定是错过了一些就在拐角处的东西。

我有一个自定义转换器,允许我执行以下操作:

cfg.CreateMap<Container<int>, int>().ConvertUsing(new ContainerConverter<Container<int>, int>());

int不是唯一的类型参数,是否有一种简洁的方式来表达:

cfg.CreateMap<Container<T>, T>().ConvertUsing(new ContainerConverter<Container<T>, T>());

无需做:

cfg.CreateMap<Container<int>, int>().ConvertUsing(new ContainerConverter<Container<int>, int>());
cfg.CreateMap<Container<long>, long>().ConvertUsing(new ContainerConverter<Container<long>, long>());
...

对于每一个T使用?

在我的情况下, 和 的属性Container<T>T是类A1, A2...B1, B2.... 映射是通过调用来执行的

B dest = mapper.Map<A, B>(source);

先感谢您。

标签: c#automapper

解决方案


如果您不介意拳击,可以使用通用转换器。

static void Main(string[] args)
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap(typeof(Container<>), typeof(object)).ConvertUsing(typeof(ContainerConverter<>));
    });
    config.AssertConfigurationIsValid();
    //config.BuildExecutionPlan(typeof(Destination), typeof(Source)).ToReadableString().Dump();
    var mapper = config.CreateMapper();
    mapper.Map<int>(new Container<int>{ Value = 12 }).Dump();
}
public class ContainerConverter<T> : ITypeConverter<Container<T>, object>
{
    public object Convert(Container<T> source, object destination, ResolutionContext c)
    {
        return source.Value;
    }
}
public class Container<T>
{
    public T Value { get; set; }
}

推荐阅读