如何初始化ASP.Net Web应用程序中引用的项目DLL中的AutoMapper配置文件
本文关键字:项目 DLL 中的 配置文件 AutoMapper 引用 初始化 ASP Net 应用程序 Web | 更新日期: 2023-09-27 17:58:35
在如何在我的项目类库(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<AutoMapperViewModelProfile>();
});
}
}
简介:
public class AutoMapperViewModelProfile : Profile
{
public override string ProfileName
{
get { return this.GetType().ToString(); }
}
protected override void Configure()
{
CreateMap<InventoryContainerHeader, InventoryContainerLabelPrintZPLViewModel>()
.ForMember(vm => vm.StatusDescription, opt => opt.MapFrom(entity => entity.InventoryContainerStatus.DisplayText))
.ForMember(dest => dest.ContainerDetails, option => option.Ignore())
;
...
}
}
一种方法是使用反射加载所有配置文件:
var assembliesToScan = 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);
}
});
您不直接引用任何一个Automapper配置文件,而是从当前AppDomain加载所有配置文件。