Use no global Mapper variable of Automapper in AfterMap

假装没事ソ 提交于 2019-12-12 06:06:23

问题


Is there a way to get the current mapping context in AutoMapper when using AfterMap?

public class DefaultMappingProfile : Profile
{
    protected override void Configure()
    {
        this.CreateMap<SomeList, List<SpecialItem>>()
            .AfterMap((src, dst) => dst.AddRange(
                 src.elem.Select(Mapper.Map<SpecialItem>)));

I tried to use .ConstructUsing(context => {}) but this gave me not the same results as when using AfterMap (!?). But I don't want to access the global variable Mapper here. Is there a way to get around accessing the global variable here?


回答1:


You could as an alternative use ConvertUsing<TSource, TDestination> such as:

CreateMap<data.BillCycle, domain.BillCycle>().ConvertUsing<BillCycleConverter>();

The class will implement ITypeConverter<TSource, TDestination> and gives you access to the mapper:

public class BillCycleConverter : ITypeConverter<data.BillCycle, domain.BillCycle>
{
    public domain.BillCycle Convert(ResolutionContext context)
    {
        context.Engine.Map<X, Y>...
    }
}

Custom Type Converters



来源:https://stackoverflow.com/questions/32267497/use-no-global-mapper-variable-of-automapper-in-aftermap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!