How to scan and auto-configure profiles in AutoMapper?

后端 未结 8 612
花落未央
花落未央 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 03:04

    Similar to @Martino's answer, but with a MapperConfiguration object. This will add all profiles from the assembly that contains the type MyProfile.

    var config = new MapperConfiguration(cfg =>
       {
          cfg.AddProfiles(typeof(MyProfile));
       });
    var mapper = config.CreateMapper();
    
    0 讨论(0)
  • 2020-12-24 03:15
     public class AutoMapperAdapter : IMapper
    {
        private readonly MapperConfigurationExpression _configurationExpression =
            new MapperConfigurationExpression();
    
        public void AssertConfigurationIsValid() { Mapper.AssertConfigurationIsValid(); }
    
        public void CreateMap<TSource, TDestination>()
        {
            _configurationExpression.CreateMap<TSource, TDestination>();
        }
    
        public void Initialize() { Mapper.Initialize(_configurationExpression); }
    
        public TDestination Map<TDestination>(object source)
        {
            return Mapper.Map<TDestination>(source);
        }
    }
    
    0 讨论(0)
提交回复
热议问题