1

I am using global configuration for Automapper profile mapping.

public class StudentProfile : Profile
{
    public StudentProfile()
    {
        CreateMap<Student, StudentVM>()
            .ForMember(dest => dest.school, src => src.Ignore());
    }
}

Mapper Configuration

public static class Configuration
{
    public static IMapper InitializeAutoMapper()
    {
        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new StudentProfile());
        });

        config.AssertConfigurationIsValid();
        return config.CreateMapper();
    }
}

Now I am adding .AddAfterMapAction using Expression.

static void Main(string[] args)
    {
        try
        {
            var mapper = Configuration.InitializeAutoMapper();

            foreach (var item in mapper.ConfigurationProvider.GetAllTypeMaps())
            {
                Expression<Action<int>> beforeMapAction = (x) => Test(x);
                item.AddAfterMapAction(beforeMapAction);
            }

            var dest = mapper.Map<Student, StudentVM>(StudentService.GetStudent());

            Console.ReadLine();
        }
        catch (Exception ex)
        {
        }
    }
    public static void Test(int x)
    {
        Console.WriteLine("X = {0}", x);
    }

It is not invoking the Test method when I am mapping using this line: var dest = mapper.Map<Student, StudentVM>(StudentService.GetStudent());

Am I doing anything wrong here. As it should call the Test method while mapping.

Fahad Mahmood
  • 350
  • 2
  • 5
  • 20

1 Answers1

2

You can't modify maps after MappingConfiguration is instantiated. Once a TypeMap is built, the execution plan is created and can't change.

You need to move that AfterMap configuration into where you're configuring.

Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69