Search code examples
c#automapperautomapper-4

Automapper -AutoMapper.AutoMapperMappingException


I trying out Automapper, with a really easy mapping, but it does not work. I am trying to map a System.Security.Claims.Claim type to another type ClaimItem:

public class ClaimItem
{
    public string Type { get; set; }
    public string Value { get; set; }
}

But I always get:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types: Claim -> ClaimItem System.Security.Claims.Claim -> CommonAuth.ClaimItem

Destination path: ClaimItem

Source value: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth: 05.05.2016

Here is my configuration:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Claim, ClaimItem>(MemberList.Destination);
});

config.AssertConfigurationIsValid();

var cls = getClaims();
List<ClaimItem> list = new List<ClaimItem>();
cls.ForEach(cl => list.Add(Mapper.Map<ClaimItem>(cl)));

Solution

  • From the documentation you must create mapper from config. So you should have in your code smth like this

     private static Mapper _mapper;
        public static Mapper Mapper
        {
            get
            {
                if (_mapper == null)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Claim, ClaimItem>(MemberList.Destination);
                    });
    
                    config.AssertConfigurationIsValid();
                    _mapper = config.CreateMapper();
                }
                return _mapper;
            }
        }
    

    This means that if you have static Mapper it hould be created from config which you create