private void AddMapsCore(IEnumerable <Assembly> assembliesToScan) { var allTypes = assembliesToScan.Where(a => !a.IsDynamic && a != typeof(NamedProfile).Assembly).SelectMany(a => a.GetDefinedTypes()).ToArray(); var autoMapAttributeProfile = new NamedProfile(nameof(AutoMapAttribute)); foreach (var type in allTypes) { if (typeof(Profile).IsAssignableFrom(type) && !type.IsAbstract) { AddProfile(type.AsType()); } foreach (var autoMapAttribute in type.GetCustomAttributes <AutoMapAttribute>()) { var mappingExpression = (MappingExpression)autoMapAttributeProfile.CreateMap(autoMapAttribute.SourceType, type); autoMapAttribute.ApplyConfiguration(mappingExpression); foreach (var memberInfo in type.GetMembers(BindingFlags.Public | BindingFlags.Instance)) { foreach (var memberConfigurationProvider in memberInfo.GetCustomAttributes().OfType <IMemberConfigurationProvider>()) { mappingExpression.ForMember(memberInfo, cfg => memberConfigurationProvider.ApplyConfiguration(cfg)); } } } } AddProfile(autoMapAttributeProfile); }
//taken from https://github.com/AutoMapper/AutoMapper/blob/master/src/AutoMapper/Configuration/MapperConfigurationExpression.cs private Profile HandleAutoMapTypes(params Type[] types) { var autoMapAttributeProfile = new NamedProfile(nameof(AutoMapAttribute)); foreach (var type in types) { foreach (var autoMapAttribute in type.GetCustomAttributes <AutoMapAttribute>()) { var mappingExpression = (MappingExpression)autoMapAttributeProfile.CreateMap(autoMapAttribute.SourceType, type); autoMapAttribute.ApplyConfiguration(mappingExpression); foreach (var memberInfo in type.GetMembers(BindingFlags.Public | BindingFlags.Instance)) { foreach (var memberConfigurationProvider in memberInfo.GetCustomAttributes().OfType <IMemberConfigurationProvider>()) { mappingExpression.ForMember(memberInfo.Name, cfg => memberConfigurationProvider.ApplyConfiguration(cfg)); } } } } return(autoMapAttributeProfile); }