关于如何在我的项目类库(dll)中使用自动映射器有点困难。请参阅下面我的整体解决方案的结构。
WebApp 启动,并在 Global.asax App Start 中调用 AutoMapper.Configure() 方法来添加映射配置文件。现在我只是添加 Services.AutoMapperViewModelProfile。但我需要以某种方式考虑每个 WebStoreAdapter 中的配置文件(下面示例中的 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>();
});
}
}
Profile:
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 加载所有配置文件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)