簡體   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