1

I apologize for not being clear in the question title. I will try to explain in simple words:

I am creating a Mapper instance inside my function with mapping specified:

//omitted rest of the mapping to make the code simpler 
private TRADELINE MapTradeLine(Tradeline tradeLine, TradelineMeta tradelineMeta)
{
    MapperConfiguration configMapTradeline = new MapperConfiguration(
     cfg =>
     {
         cfg.CreateMap<Tradeline, TRADELINE>()       
         .ForPath(dest => dest.TLSOURCE, opt => opt.MapFrom(src => src.Source))              
         .ForPath(dest => dest.REQID, opt => opt.MapFrom(src => tradelineMeta.RequestId))        
     });
    IMapper mapperTradeline = configMapTradeline.CreateMapper();    
    return mapperTradeline.Map<Tradeline, TRADELINE>(tradeLine);
}

This is working fine. Though would like to move this code to Profile

Something like this:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        .CreateMap<Tradeline, TRADELINE>()       
         .ForPath(dest => dest.TLSOURCE, opt => opt.MapFrom(src => src.Source))              
         .ForPath(dest => dest.REQID, opt => opt.MapFrom(src => tradelineMeta.RequestId));
    }
}

public static class MappingHelper
{
    private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
            cfg.AddProfile<MappingProfile>();
        });
        var mapper = config.CreateMapper();
        return mapper;
    });

    public static IMapper Mapper => Lazy.Value;
}

After that, I can use IMapper instance to perform the mapping. My objective is to avoid initialization of AutoMapper for each method call.

I am stuck on how to specify tradelineMeta.RequestId if I go with the Profile approach.

Is it possible?

Shaggy
  • 5,422
  • 28
  • 98
  • 163

1 Answers1

1

As mentioned in the link provided by @Lucian Bargaoanu and this question i was able to figure it out:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        .CreateMap<Tradeline, TRADELINE>()       
         .ForPath(dest => dest.TLSOURCE, opt => opt.MapFrom(src => src.Source))                       
         .ForMember(dest => dest.REQID, opt => opt.MapFrom((src, dest, destMember, context) => context.Items["REQID"]))
    }
}

Usage:

return MappingHelper.Mapper.Map<Tradeline, TRADELINE>(tradeLine, opt =>
     {                 
         opt.Items["REQID"] = tradelineMeta.RequestId;                 
     });
Shaggy
  • 5,422
  • 28
  • 98
  • 163