How to scan and auto-configure profiles in AutoMapper?

后端 未结 8 676
花落未央
花落未央 2020-12-24 02:50

Is there any way to auto-configue Automapper to scan for all profiles in namespace/assembly? What I would like to do is to add mapping profiles to AutoMapper from given asse

8条回答
  •  半阙折子戏
    2020-12-24 02:57

    I found this post while searching as well, but this is how I implemented an auto mapping scheme:

    public class MyCustomMap : Profile
    {
        protected override void Configure()
        {
            CreateMap()
                .ForMember(dest => dest.Phone,
                            opt => opt.MapFrom(
                            src => src.PhoneAreaCode + src.PhoneFirstThree + src.PhoneLastFour));
        }
    }
    
    public static class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x => GetConfiguration(Mapper.Configuration));
        }
    
        private static void GetConfiguration(IConfiguration configuration)
        {
            var profiles = typeof(MyCustomMap).Assembly.GetTypes().Where(x => typeof(Profile).IsAssignableFrom(x));
            foreach (var profile in profiles)
            {
                configuration.AddProfile(Activator.CreateInstance(profile) as Profile);
            }
        }
    }
    

    So when my application starts, all I call is

    AutoMapperConfiguration.Configure(); 
    

    And all my maps are registered.

提交回复
热议问题