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

Cha*_*son 4 c# asp.net automapper automapper-4

在我的项目类库(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
Run Code Online (Sandbox Code Playgroud)

从Global.asax调用初始化:

public static class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(am =>
        {
            am.AddProfile<AutoMapperViewModelProfile>();
        });
    }    
}
Run Code Online (Sandbox Code Playgroud)

轮廓:

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())
                ;
        ...
   }
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 10

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

        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);
            }
        });
Run Code Online (Sandbox Code Playgroud)

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