繁体   English   中英

如何使用自动映射器映射对象,但目标对象根据配置看起来不同?

[英]Howto to map an object with automapper but have the destination object look different depending on configuration?

我相信我的问题有一个简单的解决方案,但我没有看到它,所以我需要一些帮助来照亮我的道路。

我们使用 automapper 将我们的内部对象映射到 fhir 对象以与不同的系统进行通信。 现在其中一个系统已经扩展,因此它需要相同的 fhir 对象,但内容略有不同。 这意味着如果我们的系统配置为使用旧版本,则 fhir 对象必须看起来像以前一样。 如果系统已经配置为支持新版本,则fhir对象必须填充其他内容以满足新系统要求。

在配置文件类中,无法使用外部配置,因此不可能根据我的系统配置填充对象(据我所知)。 要映射的对象没有改变,只有内容改变了,所以将不同的映射添加到自动映射器配置将不起作用,因为自动映射器的实现没有区别。 我尝试了 Before- 和 AfterMapping-action,但遇到错误说地图丢失了。 那么实现这一目标的最佳方法是什么?

假设您将使用IConfiguration来检测您的系统配置为使用哪个版本。

您可以将此信息传递到您可以在映射器配置中访问它的ResolutionContext

public class Service
{
    private readonly IConfiguration configuration;
    private readonly IMapper mapper;

    public Service(IConfiguration configuration, IMapper mapper)
    {
        this.configuration = configuration;
        this.mapper = mapper;
    }

    public DoSomething()
    {
        SourceClass source = new();

        DestinationClass destination = mapper.Map<DestinationClass>(
            source,
            // Here we pass the info whether to use the old or the new version.
            options =>
            options.Items["UseNewVersion"] =
                configuration.GetValue<bool>("UseNewVersion")
        );
    }
}

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<SourceClass, DestinationClass>()
            .ForMember(
                destination => destination.Property,
                (source, destination, destinationMember, context) =>
                {
                    // Here we get whether to use the old or the new version.
                    bool useNewVersion = (bool)context.Items["UseNewVersion"];

                    return useNewVersion ? "NEW" : "OLD";
                }
            );
    }
}

这两个Items属性都是Dictionary<string, object>类型。

  • IMappingOperationOptions.Items
  • ResolutionContext.Items

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM