自动映射器从非泛型映射到泛型

automapper map from non generic type to generic type

是否可以(以及如何)创建从非通用类型到通用类型的映射? 假设我们有:

public interface IFoo
{
     string Foo { get; set; }
}

public interface IGenericFoo<TDestination> where TDestination : class
{
     string Baboon { get; set; }
}

我尝试通过这样做来使用开放泛型 (https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics):

CreateMap(typeof(IFoo), typeof(IGenericFoo<>)

但在运行时失败并出现以下错误:

{"The type or method has 1 generic parameter(s), but 0 generic argument(s) were provided. A generic argument must be provided for each generic parameter."}

Automapper 版本:4.2.1

这仅适用于 AutoMapper 版本 5.x 及更高版本。这是一个工作示例:

using AutoMapper;
using System;

public class Program
{
    public class Source : IFoo
    {
        public string Foo { get; set; }
    }

    public class Destination<T> : IGenericFoo<T> where T : class
    {
        public string Baboon { get; set; }
    }

    public interface IFoo
    {
        string Foo { get; set; }
    }

    public interface IGenericFoo<TDestination> where TDestination : class
    {
        string Baboon { get; set; }
    }

    public static void Main()
    {
        // Create the mapping
        Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source), typeof(Destination<>)));

        var source = new Source { Foo = "foo" };

        var dest = Mapper.Map<Source, Destination<object>>(source);

        Console.WriteLine(dest.Baboon);
    }
}

https://dotnetfiddle.net/wpBp7k