How to add existing profile in the mapper configuration using Refection(In a generic way)

I have a separate classes for mapping between source and destination. For e.g.


public class RegistrationMapping
    public static void Map(IProfileExpression profile)
       profile.CreateMap<DB_Registration, Registration>()
            .ForMember(x => x.EMP_ID, map => map.MapFrom(c => c.employeeID))
            .ForMember(x => x.MOB_NO, map => map.MapFrom(c => c.Mobile))
            .ForMember(x => x.EMAIL_ID, map => map.MapFrom(c => c.EmailID))

In a similar fashion, I have classes for other mappings as well.

Now in my repository, I want to use like this,

// I want to achieve below code in a generic way. 
var config = new MapperConfiguration(cfg => cfg.AddProfile(/*RegistrationMapping goes here*/)); 
var mappedConfigurations = config.GetAllTypeMaps(); // This line of code is needed for my other purpose(get unmapped properties) 

Any help would be highly appreciated.

1 answer

  • answered 2019-10-08 05:20 krema

    AutoMapper allows profiles to be loaded by passing the assembly, the assembly name, or type contained in the assembly.

    Your RegistrationMapping class and others have to be inherited from AutoMapper.Profile.

    You can load your profiles like this:

    By type:

    Mapper.Initialize(x => x.AddProfile<RegistrationMapping>()); 
    Mapper.Initialize(x => x.AddProfile(typeof(RegistrationMapping))); 

    By instance:

    Mapper.Initialize(x => x.AddProfiles(new List<Profile> { new RegistrationMapping() })); 
    Mapper.Initialize(x => x.AddProfile(new RegistrationMapping())); 

    By assembly name:

    Mapper.Initialize(x => x.AddMaps("MyApplication.RegistrationMapping"));
    Mapper.Initialize(x => x.AddMaps(new string[] {"MyApplication.RegistrationMapping"}));

    By assembly:

    Mapper.Initialize(x => x.AddMaps(Assembly.GetExecutingAssembly()));

    If you want to load all profiles from loaded assemblies:

    var profiles = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes().Where(type => typeof(Profile).IsAssignableFrom(type)));
    Mapper.Initialize(x => x.AddMaps(profiles));

    For more information please see also the AutoMapper Configuration documentation and the source code.