1

I want to call a specific method xyz() on every property mapped by generic mapper configuration. Is this possible?

I am using Automapper v 9. Purpose is to call the method on each property mapped by Automapper to check add remove data at runtime.

public static IMapper CreateMapper<TSource, TDestination>()
        {
            var config = new MapperConfiguration(
                cfg =>
                {
                    cfg.Advanced.AllowAdditiveTypeMapCreation = true;
                    cfg.AllowNullDestinationValues = true;
                    cfg.AllowNullCollections = true;
                    cfg.CreateMap<TSource, TDestination>()
                    .PreserveReferences()
                });

            config.AssertConfigurationIsValid();

            return config.CreateMapper();
        }
Fahad Mahmood
  • 350
  • 2
  • 5
  • 20
  • 1
    It doesn't _sound_ like a good idea. Perhaps you can explain in greater detail what you're trying to achieve here. – Lucian Bargaoanu Feb 07 '20 at 09:19
  • You can use beforeMap that will definitely match with your requirement – Nikunj Patel Feb 08 '20 at 14:55
  • Is aftermap a good workaround because it will use reflection and it is not very optimal solution. I don't have sound knowledge on reflection performance but if I have to search for a property using reflection then I don't need to call for separate method I can easily map using source and destination. – Fahad Mahmood Feb 18 '20 at 15:49
  • Sorry for late response @LucianBargaoanu. Actually I have defined a generic mapper for multiple classes with inner child collection using ICollection interface. I have create a new question for that https://stackoverflow.com/questions/60212096/automapper-not-mapping-mapping-properties. – Fahad Mahmood Feb 18 '20 at 15:53

2 Answers2

0

Yes of-course you can do it upon your need I mean before map or after map globally ! Use this official Auto-mapper Doc. for reference

Nikunj Patel
  • 249
  • 3
  • 13
0

Yes, you can call what you want. I already use like this.

  CreateMap<UserMessage, USER>()                    
                .ForMember(dest => dest.X, opts => opts.MapFrom(src => src.A!= null ? MessageExtensions.GetCvTitle(src.A) : string.Empty))
                .ForMember(dest => dest.Y, opts => opts.MapFrom(src => MessageExtensions.GetFacultyName(src.B)))
                .ForMember(dest => dest.Z, opts => opts.MapFrom(src => MessageExtensions.GetDepartmentName(src.C)))
                .ForMember(dest => dest.T, opts => opts.MapFrom(src => MessageExtensions.GetProgramName(src.D)))
Unknown Artist
  • 143
  • 1
  • 9
  • Thanks for your answer but I need it for generic configuration as you can see it in my source code snapshot. ForMember is not useful in generic case. – Fahad Mahmood Feb 18 '20 at 15:47