如何在ASP.Net webapp中引用的项目DLL中初始化AutoMapper配置文件

在我的项目类库(dll)中如何使用automapper苦苦挣扎。 请参阅下面我的整体解决方案的结构。

WebApp启动,在Global.asax App Start中,调用AutoMapper.Configure()方法以添加映射配置文件。 现在我只是添加Services.AutoMapperViewModelProfile。 但我需要以某种方式考虑每个WebStoreAdapters中的配置文件(下例中的BigCommerce和Shopify)。 我希望不要在WebApp中添加对每个WebStoreAdapter的引用,只是为了能够在AutoMapperConfig中添加配置文件。 如果我在WebStoreFactory中添加对AutoMapper.Initialize的另一个调用,它将覆盖WebApp中的一个。

还有其他方式,我错过或完全偏离这里以其他方式?

WebApp - AutoMapperConfig - AddProfile Services.AutoMapperViewModelProfile Services.dll - AutoMapperViewModelProfile Scheduler.dll (uses HangFire to execute cron jobs to get data from shop carts. Its UI is accessed via the WebApp) WebStoreAdapter.dll -WebStoreFactory BigCommerceAdapter.dll - AutoMapperBigCommerceDTOProfile ShopifyAdapter.dll - AutoMapperShopifyDTOProfile 

从Global.asax调用初始化:

 public static class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize(am => { am.AddProfile(); }); } } 

轮廓:

 public class AutoMapperViewModelProfile : Profile { public override string ProfileName { get { return this.GetType().ToString(); } } protected override void Configure() { CreateMap() .ForMember(vm => vm.StatusDescription, opt => opt.MapFrom(entity => entity.InventoryContainerStatus.DisplayText)) .ForMember(dest => dest.ContainerDetails, option => option.Ignore()) ; ... } } 

一种方法是使用reflection来加载所有配置文件:

  var assembliesToScane = AppDomain.CurrentDomain.GetAssemblies(); var allTypes = assembliesToScan.SelectMany(a => a.ExportedTypes).ToArray(); var profiles = allTypes .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo())) .Where(t => !t.GetTypeInfo().IsAbstract); Mapper.Initialize(cfg => { foreach (var profile in profiles) { cfg.AddProfile(profile); } }); 

您不直接引用任何一个配置文件,只是从当前AppDomain加载所有配置文件。