Throw error/warning when CreateMap<S, T> is already defined

Viewed 73

The other day I have been fighting with a non-mapped property by using AutoMapper.

After researching over the application, it ends up being that there was a CreateMap<S, T> already defined that was overriding (or reading first) the one that I was trying to configure.

The situation looks like this:

public MainProfile()
{
    CreateMap<Class1, Class2>()
        .ForMember(x => x.Property1, opt => opt.MapFrom(s => s.Property1Foo)
        .ForMember(x => x.Property2, opt => opt.MapFrom(s => s.Property2Foo); /*Here is the thing!*/;
}

And then there was another class which does the following:

public SecondaryProfile()
{
    CreateMap<Class1, Class2>()
        .ForMember(x => x.Property1, opt => opt.MapFrom(s => s.Property1Foo);           
}

In my case, when I did:

var class2Object = mapper.Map<Class2>(class1Instance);

It is taking the definition from SecondaryProfile.cs but I was attempting to do it on MainProfile.cs, so the Property2 is not getting mapped.

This doesn't give you any warning, any error and also compiles fine. On top of that, this can introduce a hard to find bug, so I wonder how can I avoid this situation?

Is there a configuration that you can do to say AutoMapper to warn you on this?

0 Answers
Related