How to scan and auto-configure profiles in AutoMapper?

后端 未结 8 678
花落未央
花落未央 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 have it like this, don't know if it is the best way but it works very well on pretty large project.

    public class AutoMapperGlobalConfiguration : IGlobalConfiguration
        {
            private AutoMapper.IConfiguration _configuration;
    
            public AutoMapperGlobalConfiguration(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public void Configure()
            {
                //add all defined profiles
                var query = this.GetType().Assembly.GetExportedTypes()
                    .Where(x => x.CanBeCastTo(typeof(AutoMapper.Profile)));
    
                _configuration.RecognizePostfixes("Id");
    
                foreach (Type type in query)
                {
                    _configuration.AddProfile(ObjectFactory.GetInstance(type).As());
                }
    
                //create maps for all Id2Entity converters
                MapAllEntities(_configuration);
    
               Mapper.AssertConfigurationIsValid();
            }
    
            private static void MapAllEntities(IProfileExpression configuration)
            {
                //get all types from the SR.Domain assembly and create maps that
                //convert int -> instance of the type using Id2EntityConverter
                var openType = typeof(Id2EntityConverter<>);
                var idType = typeof(int);
                var persistentEntties = typeof(SR.Domain.Policy.Entities.Bid).Assembly.GetTypes()
                   .Where(t => typeof(EntityBase).IsAssignableFrom(t))
                   .Select(t => new
                   {
                       EntityType = t,
                       ConverterType = openType.MakeGenericType(t)
                   });
                foreach (var e in persistentEntties)
                {
                    var map = configuration.CreateMap(idType, e.EntityType);
                    map.ConvertUsing(e.ConverterType);
                }
            }
        }
    }
    

提交回复
热议问题