Automapper 4.2 example

Automapper 4.2 has marked the static API as obsolete so things should be done slightly differently than before as the static API will be dropped completely in version 5. Creating maps without the static API in 4.2 is simple. Below is an automapper 4.2 example which creates two maps and uses one with a mapper.Map statement, where mapper is a call to an instance not a static API.

var config = new MapperConfiguration(cfg =>
{
 cfg.CreateMap<PlayerViewModel, PlayerDTO>()
 .ForMember(dst => dst.NickName, opt => opt.MapFrom(src => src.FanName))
 .ForMember(dst => dst.YearsOld, opt => opt.MapFrom(src => src.Age));
 
 cfg.CreateMap<TeamViewModel, TeamDTO>()
 .ForMember(dst => dst.TeamName, opt => opt.MapFrom(src => src.Name))
 .ForMember(dst => dst.CoachFullName, opt => opt.MapFrom(src =>   src.ManagerFullName));
});

config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
TeamDTO DTO = mapper.Map<TeamDTO>(TeamViewModel.getTeamViewModel());

The first block would go in global.asax or similar. The second block is used throughout your application to actually do the conversions from source to destination objects.

2 thoughts on “Automapper 4.2 example”

  1. Hi Dave,
    Could you explain bit more where the ‘config’, mentioned in your second block is coming from?
    Thanks, KWHJ

  2. Hi Dave,
    I couldn’t have it somebody else figuring out what’s wrong. It was a bit of a puzzle… but, I reached my goal. I would suggest you should give a little bit more information what people should do extra in block 2.

    According https://github.com/AutoMapper/AutoMapper/wiki/Migrating-from-static-API: the second block (for 4.2.x and later), people should instantiate on each desired spot (controllers):
    ***********begin missing lines in block 2***************
    var config = new MapperConfiguration(cfg => {
    cfg.AddProfile();
    cfg.CreateMap();
    });
    ************end missing lines in block 2***************
    IEnumeralbe = config
    .CreateMapper()
    .Map(new Source());

    This implementation in conjunction with your suggestion in block 1 ; the obsolete warnings are gone and their app should work as expected.

    You brought on right track to solve this puzzle, thanks anyway.

    KWHJ

Leave a Reply

Your email address will not be published. Required fields are marked *