Home > Net >  Multiple Automapper Custom Resolvers Only One Is Called
Multiple Automapper Custom Resolvers Only One Is Called

Time:02-10

I am using custom resolvers to fill up an Ids property in the destination class. But, only one of the custom resolvers is getting called. (I put a break point in each.)

So, in my Automapper (v 10.1.1) mappings, I have:

.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property1ToIdsResolver>())
.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property2ToIdsResolver>())

I am doing this because I want to pull ids from Class1 and Class2 and put them all in the destination's Ids list.

They are setup as such:

public class Property1ToIdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)

and

public class Property2ToIdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)

In both, I check if Ids is null and if so, new up a List of Guids and fill it. If not, I append to it.

With the current .ForMember setup above, Property1ToIdsResolver's breakpoint does not get hit, but Property2ToIdsResolver does.

If I change it to:

.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property2ToIdsResolver>())
.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property1ToIdsResolver>())

Property2ToIdsResolver's breakpoint does not get hit, but Property1ToIdsResolver does.

How can I get both resolvers to be called?

CodePudding user response:

As Lucian commented, it looks like you cannot have multiple resolvers to the same property. So, to keep the logic separated, I kept the two resolvers, Property1ToIdsResolver and Property2ToIdsResolver. I created a third encompassing resolver called IdsResolver which just calls the other two.

public class IdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    private IValueResolver<SrcClass, DestClass, List<Guid>> property1ToIdsResolver = new Property1ToIdsResolver();
    private IValueResolver<SrcClass, DestClass, List<Guid>> property2ToIdsResolver = new Property2ToIdsResolver();

    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)
    {
        var ids = property1ToIdsResolver.Resolve(src, dest, member, context);
        ids.AddRange(property2ToIdsResolver.Resolve(src, dest, member, context));

        return ids;
    }
}

Other people may prefer to have a single resolver with private methods, up to you. But, this is what I did.

  •  Tags:  
  • Related