Pass different AutoMapper context per nested mapping

Viewed 157

I know we can set the Context items when we call Map(), and it will be available to every map operation. Is there a way to change those context items during mapping?

Suppose I have these source types:

public class OuterSource {
    public string TimeZone { get; set; }
    public string Name { get; set; }
    public InnerSource[] InnerArray { get; set; }
}

public class InnerSource {
    public DateTime Created { get; set; }
    public string Message { get; set; }
}

and these destination types:

public class OuterDest {
    public string Name { get; set; }
    public InnerDest[] InnerArray { get; set; }
}

public class InnerDest {
    public DateTime Created { get; set; }
    public string Message { get; set; }
}

The only difference is that InnerSource.Created is in UTC and I want to map it to the local time zone. However the time zone is in OuterSource, not InnerSource.

Normally, I would set up my mappers like so:

CreateMap<OuterSource, OuterDest>();
CreateMap<InnerSource, InnerDest>();

But that wouldn't work because when it comes to mapping InnerSource to InnerDest it does not have access to OuterSource.TimeZone.

So I'm currently forced to set my mapping like so:

CreateMap<OuterSource, OuterDest>()
    .ForMember(dest => dest.InnerArray, opt => opt.ResolveUsing(
        //loop through source.InnerArray and do the datetime
        //conversion manually
));

I consider that a code smell. What I would love to do is to pass the timezone to the nested mapping somehow. I would appreciate any pointers towards that direction.

0 Answers
Related