自动映射器:最新版本中缺少映射到未知目的地/GetAllTypeMaps

Mar*_*der 0 c# automapper

测试使用:Automapper 10.1.2-alpha.0.4(MyGet Build)

我们希望将 DomainEvents 映射到没有任何基类的公共合约,并将它们发布到消息队列/主题。

由于它应该是动态映射,因此在映射到目标合约时我们不知道目标类型。

对于这种情况,我们在这篇文章中提供了以下解决方案: 如何使用 Automapper 将对象映射到未知的目标类型?如下:

public async Task Publish(DomainEvent domainEvent)
{
    this.logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);

    try
    {
        var publicEvent = this.MapToContract(domainEvent);

        await this.publishEndpoint.Publish(publicEvent);
    }
    catch (Exception ex)
    {
        this.logger.LogError("Unexpected exception while publishing domain event.", ex);
    }
}

private object MapToContract(object source)
{
    var sourceType = source.GetType();
    TypeMap? typeMap = null;

    try
    {
        typeMap = this.mapper.ConfigurationProvider
            .GetAllTypeMaps()
            .SingleOrDefault(map => map.SourceType == sourceType);
    }
    catch (InvalidOperationException)
    {
        throw new Exception($"Multiple types for {sourceType.FullName} available. Only one allowed");
    }

    return typeMap is null
        ? throw new Exception($"No type map for {sourceType.FullName} found!")
        : this.mapper.Map(source, sourceType, typeMap.DestinationType);
}
Run Code Online (Sandbox Code Playgroud)

Publish(DomainEvent domainEvent)每当引发域事件时,就会被称为事件接收器。

自上一个版本以来,我们无法MapToContract再使用该方法,因为该GetAllTypeMaps方法不可用。我无法找到任何解决方法。

公共事件类示例:

public record EmployeeCreated(int Id, string Name, string FirstName);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 12

好的,有同样的问题。解决方案是使用内部扩展方法,如下所示(请参阅https://docs.automapper.org/en/stable/11.0-Upgrade-Guide.html?highlight=internal#forallmaps-forallpropertymaps-advanced-and-other-missing- API ):

using AutoMapper.Internal;

...

this.mapper.ConfigurationProvider
   .Internal()
   .GetAllTypeMaps()
   ...
Run Code Online (Sandbox Code Playgroud)