automapper - 如何构建 AutoMapper 映射以在目标类构造函数中传递参数

标签 automapper

如果我有这组源类怎么办:

namespace Source {

    class CA
    {
        public CB B { get; set; }
    }

    class CB {}

}

目标类集的唯一区别是CB在构造函数中接受CA引用(CA具有相同的结构):

namespace Destination {

    class CA
    {
       public CB B { get; set; }
    }

    class CB
    {
       public CB(CA parent) { ... }
    }
}

如何使用 AutoMapper 为此类类构建静态映射?我的意思是对整个应用程序运行一次的东西,而不是每个 CA、CB 实例。

我知道我可以在每个具有 CA 目标实例的映射之前动态地这样做:

var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);

config.CreateMap<Source.CB, Destination.CB>()
        .ConstructUsing((ResolutionContext cntx) => 
            new Destination.CB(instanceOfCADestination));

但由于性能问题,这对我不起作用。

最佳答案

除了在映射之前实例化 CA,将其存储到 IMappingOperationOptions.Options.Items 集合并在 ConstructUsing 中获取之外,没有找到更好的方法

Mapper.CreateMap<Source.CB, Destination.CB>()
      .ConstructUsing(cntx => 
              new Destination.CB((Destination.CA)cntx.Options.Items["CADestRef]));

var destCAInstance = new Destination.CA();

var destCBInstance = 
       Mapper.Map<Destination.CB>(Source.CB, 
                                  opts => opts.Items["CADestRef"] = destCAInstance);

这样我就可以让整个映射保持静态。 我个人不喜欢这个解决方案,但它确实有效。不过,如果您知道更好的,请告诉我。

关于automapper - 如何构建 AutoMapper 映射以在目标类构造函数中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35583828/

相关文章:

基于目标值的 C# AutoMapper 条件映射

c# - 使用 AutoMapper 找出映射的属性

c# - AutoMapper:将接口(interface)映射到抽象类——这可能吗?

c# - Automapper UseDestinationValue

c# - 如何将 ProjectTo 从基本类型转换为仅在运行时已知的类型?

c# - 使用 Automapper 映射后嵌套对象成员为 null

c# - Automapper 自定义解析器

c# - Automapper 无法映射到 IEnumerable

c# - 将 Automapper 与 ASP.NET Core 结合使用

asp.net - Automapper 有什么用?