如何使用AutoMapper的新IValueResolver?

Pad*_*ySe 19 c# automapper automapper-5

我不知道如何IValueResolver在新版本的AutoMapper中使用新界面.也许我在以前版本的AutoMapper中使用它们不正确......

我有很多模型类,其中一些是使用sqlmetal从几个数据库服务器上的几个数据库生成的.

其中一些类具有字符串属性,PublicationCode用于标识订阅,商品或发票或其他任何内容所属的发布.

该发布可以存在于两个系统(旧系统和新系统)中的任何一个系统中,因此我在目标模型类上有一个bool属性,用于指示发布是在旧系统还是新系统中.

使用AutoMapper的旧版本(<5?),我使用的ValueResolver<string, bool>,其采取了PublicationCode作为输入参数,并且返回一个bool指示出版物(旧的或新的系统)的位置.

使用AutoMapper的新版本(5+?),这似乎不再可能.新的IValueResolver需要我拥有的源模型和目标模型的每个组合的唯一实现,src.PublicationCode需要将其解析为dst.IsInNewSystem.

我只是试图以错误的方式使用值解析器吗?有没有更好的办法?我想使用解析器的主要原因是我更喜欢将服务注入到构造函数中,而不必DependencyResolver在代码中使用等(我使用的是Autofac).

目前,我通过以下方式使用它:

// Class from Linq-to-SQL, non-related properties removed.
public class FindCustomerServiceSellOffers {
    public string PublicationCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我拥有的几个数据模型类之一,它包含一个PublicationCode属性).此特定类映射到此视图模型:

public class SalesPitchViewModel {
    public bool IsInNewSystem { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这两个类的映射定义是(其中expression是IProfileExpression),删除了不相关的映射:

expression.CreateMap<FindCustomerServiceSellOffers, SalesPitchViewModel>()
          .ForMember(d => d.IsInNewSystem, o => o.ResolveUsing<PublicationSystemResolver>().FromMember(s => s.PublicationCode));
Run Code Online (Sandbox Code Playgroud)

解析器:

public class PublicationSystemResolver : ValueResolver<string, bool>
{
    private readonly PublicationService _publicationService;
    public PublicationSystemResolver(PublicationService publicationService)
    {
        _publicationService = publicationService;
    }

    protected override bool ResolveCore(string publicationCode)
    {
        return _publicationService.IsInNewSystem(publicationCode);
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用映射器:

var result = context.FindCustomerServiceSellOffers.Where(o => someCriteria).Select(_mapper.Map<SalesPitchViewModel>).ToList();
Run Code Online (Sandbox Code Playgroud)

Rhu*_*orl 13

您可以通过IMemberValueResolver<object, object, string, bool>在映射配置中实现和使用它来创建更通用的值解析器.您可以像以前一样提供源属性解析功能:

public class PublicationSystemResolver : IMemberValueResolver<object, object, string, bool>
{
    private readonly PublicationService _publicationService;

    public PublicationSystemResolver(PublicationService publicationService)
    {
        this._publicationService = publicationService;
    }

    public bool Resolve(object source, object destination, string sourceMember, bool destMember, ResolutionContext context)
    {
        return _publicationService.IsInNewSystem(sourceMember);
    }
}



cfg.CreateMap<FindCustomerServiceSellOffers, SalesPitchViewModel>()
    .ForMember(dest => dest.IsInNewSystem,
        src => src.ResolveUsing<PublicationSystemResolver, string>(s => s.PublicationCode));
Run Code Online (Sandbox Code Playgroud)

  • 注意:虽然这个答案仍然完全有效,但在 AutoMapper 的更高版本中,ResolveUsing() 已被 MapFrom() 替换 (3认同)