ResolutionContext.Items InvalidOperationException #4160
-
Apologies as this is a straight duplicate of #3206 which appeared to reach consensus that something is not quite right however nothing has changed to rectify that. Whenever one makes use of ResolutionContext.Items there is a chance that the getter could throw InvalidOperationException depending on how Mapper.Map was called (with or without options action). If there was a property on ResolutionContext that indicated that the instance was the default instance there would be a nice way to handle this e.g. in a IValueResolver so that Mapper.Map could be called both with and without the options action (without having to catch the exception and carry on). Source/destination typespublic class Source
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Destination
{
public int Id { get; set; }
public string Name { get; set; }
} Mapping configurationclass MaybeOverridesNameResolver : IValueResolver<Source, Destination, string>
{
public string Resolve(Source source, Destination destination, string destMember, ResolutionContext context)
{
// context.Items getter may throw invalid operation
if (context.Items.TryGetValue("name", out var overrideName))
{
return overrideName as string;
}
return source.Name;
}
}
void Main()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(x => x.Name, dest => dest.MapFrom<MaybeOverridesNameResolver>());
});
var mapper = config.CreateMapper();
var source = new Source { Id = 42, Name = "Foo" };
// No problemo
var a = mapper.Map<Destination>(source, _ => {} );
// No problemo
var b = mapper.Map<Destination>(source, ctx => ctx.Items["name"] = "Bar");
// Throws as ResolutionContext is DefaultContext
var c = mapper.Map<Destination>(source);
} Version:9+ |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Could DefaultContext not just leave the property null and skip the invalid op? |
Beta Was this translation helpful? Give feedback.
#4125