繁体   English   中英

如何使用带有.net Core 2.2的实例API向Automapper v8添加全局配置选项

[英]How to add global configuration options to Automapper v8 using instance api with .net core 2.2

我正在使用:

  • .net核心v2.2.0
  • Microsoft.EntityFrameworkCore v2.2.4
  • 自动映射器v8.1.1
  • AutoMapper.Extensions.Microsoft.DependencyInjection v6.1.1
  • VS2017社区版v15.9.12

在我的解决方案中,我有:

  • TVC_DATA:处理所有数据访问并包含映射配置文件类
  • TVC_PORTAL:反应网络应用

我已经按照这里描述的指南使用依赖注入来设置自动映射器

因此:在ConfigureServices方法中TVC_PORTAL的startup.cs中,我有:

services.AddAutoMapper(typeof(AutomapProfileGen));

我使用AutoMapProfileGen的地方是AddAutoMapper用来定位其他概要文件所在的TVC_DATA程序集的标记类型之一。

在我的ObjectController中,我注入了IMapper:

public ObjectController(IHostingEnvironment environment, IMapper mapper)
{
        _hostingEnvironment = environment;            
        _mapper = mapper;
}

我稍后会使用映射器:

IEnumerable<ObjectViewType> vList = _mapper.Map<IEnumerable<ObjectType>, IEnumerable<ObjectViewType>>(mList);

我的个人资料非常简单,例如:

public class AutomapProfileSrc : Profile
{
    public AutomapProfileSrc()
    {
        //source data
        CreateMap<AirlineView, Airline>().ReverseMap();
        CreateMap<AirlineListView, Airline>().ReverseMap();
        CreateMap<AirportView, Airport>().ReverseMap();
        CreateMap<AirportListView, Airport>().ReverseMap();
        CreateMap<CountryView, Country>().ReverseMap();
        CreateMap<CountryListView, Country>().ReverseMap();
    }
}

我的问题:我想为自动映射器设置一些全局配置选项,但无法弄清楚在何处/如何设置它们。 例如:我想将ValidateInlineMaps设置为false(因为在AssertConfigurationIsValid抛出“成员未映射”异常时作为解决方案被提及)。 我也想将所有地图的MaxDepth设置为1,以避免循环引用。 我试过的

1)在所有配置文件构造函数中将ValidateInlineMaps设置为false:不起作用。

public class AutomapProfileCfg : Profile
{
    public AutomapProfileCfg()
    {
        ValidateInlineMaps = false;
...

2)在ConfigureServices中创建一个MapperConfiguration对象,例如:

'var config = new MapperConfiguration(cfg =>
    {
        cfg.ForAllMaps((typeMap, mappingExpression) => {  mappingExpression.MaxDepth(1); });
        cfg.AllowNullCollections = true;
        cfg.ValidateInlineMaps = false;
        //cfg.Advanced.MaxExecutionPlanDepth = 1;
    });'

但是我不知道如何将其链接到mapper实例:仅仅创建并不会改变mapper的行为。

已经浏览了文档并在该网站上搜索了将近一天:令人沮丧,因为这看起来必须很简单....但是我无法以某种方式使其正常工作。 任何帮助将非常感激

在配置服务时,可以直接指定任何全局配置操作:

services.AddAutoMapper(cfg =>
    {
        cfg.ValidateInlineMaps = true;
        ...other config stuff

    }, typeof(AutomapProfileGen)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM