将AutoMapper更新到5.0版本会使ITypeConverter和Profiles发生冲突

本文关键字:ITypeConverter Profiles 冲突 更新 AutoMapper 版本 | 更新日期: 2023-09-27 17:54:31

我已经将以下概要文件从Automapper 4.2.1移植到5.0,将我在现在已经过时的Configure()方法中的内容移动到概要文件的构造函数中,并在表达式中更改Convert方法的签名。

public class AuthorModelToDtoProfile : Profile
{
    public AuthorModelToDtoProfile() {
        CreateMap<Author, AuthorDto>()
            .ForMember(a => a.AuthorId, o => o.MapFrom(m => m.Id))
            .ForMember(a => a.FullName, o => o.MapFrom(m => $"{m.FirstName} {m.Surname}"));
    }
}
public class BookModelToDtoProfile : Profile
{
    public BookModelToDtoProfile() {
        CreateMap<IEnumerable<Genre>, IEnumerable<int>>()
            .ConvertUsing(new GenreExpression());
    }
}
public class GenreExpression : ITypeConverter<IEnumerable<Genre>, IEnumerable<int>>
{
    public IEnumerable<int> Convert(IEnumerable<Genre> source, ResolutionContext context)
        => source.Select(g => g.Id);
}

现在,在这些更改之后,下面的配置抛出一个ArgumentException,表示它不能对IEnumerable<Genre>类型的参数使用字符串类型的表达式:

var mapperConfiguration = new MapperConfiguration(c =>
{
    c.AddProfile<BookModelToDtoProfile>();
    c.AddProfile<AuthorModelToDtoProfile>();
    c.CreateMissingTypeMaps = true;
});

奇怪的是,如果我评论一个或另一个配置文件的添加,映射器配置的创建不会抛出任何异常,它正确地映射从AuthorAuthorDto或从BookBookDto,基于我的评论,这让我认为每个配置文件本身是正确的。

我可以避免使用TypeConverter在目前的情况下,但我有更复杂的表达式,其中.ConvertUsing(...)有助于我的代码的可读性和可维护性。

有人有同样的问题或能够看到我做错了什么?

将AutoMapper更新到5.0版本会使ITypeConverter和Profiles发生冲突

已在5.0.2版修复。