问题描述
在我的项目类库(dll)中如何使用automapper进行了一些努力.请在下面查看我整体解决方案的结构.
Struggling a little on how to use automapper in my project class libraries (dlls). See my structure of my overall solution below.
WebApp启动,并在Global.asax App Start中,调用AutoMapper.Configure()方法来添加映射配置文件.现在,我只是添加Services.AutoMapperViewModelProfile.但是我需要以某种方式考虑每个WebStoreAdapters中的配置文件(在下面的示例中为BigCommerce和Shopify).我希望不为WebApp中的每个WebStoreAdapter添加引用,只是为了能够在AutoMapperConfig期间添加配置文件.如果我在WebStoreFactory中向AutoMapper.Initialize添加另一个调用,它将覆盖WebApp中的那个调用.
The WebApp fires up, and in Global.asax App Start, the AutoMapper.Configure() method is called to add the mapping profiles. For now I am just adding the Services.AutoMapperViewModelProfile. But I need to somehow account for the profiles in each of the WebStoreAdapters (BigCommerce and Shopify in the example below). I was hoping not to add references to each WebStoreAdapter in WebApp, just for the sake of being able to add the profiles during the AutoMapperConfig. If I add another call to AutoMapper.Initialize in WebStoreFactory, it overrides the one in WebApp.
我是否还有另一种方式会以某种其他方式失踪或完全不在基地?
Is there another way that I am missing or totally off base here in some other way?
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中调用初始化:
Initializing as called from 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())
;
...
}
}
推荐答案
一种方法是使用反射来加载所有配置文件:
One way to do this is to use reflection to load up all profiles:
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加载所有配置文件.
You don't directly reference any one Automapper profile, but just load all Profile's from the current AppDomain.
这篇关于如何在ASP.Net Webapp中引用的项目DLL中初始化AutoMapper配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!