繁体   English   中英

启动时未加载 Automapper 配置文件?

[英]Automapper Profiles not being loaded in Startup?

我正在使用:

  • 自动映射器 6.1.1
  • AutoMapper.Extensions.Microsoft.DependencyInjection 3.0.1

似乎我的配置文件没有被加载,每次我调用 mapper.map 我都会得到AutoMapper.AutoMapperMappingException: 'Missing type map configuration or unsupported mapping。'

这里是我的 Startup.cs 类 ConfigureServices 方法

 // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        //register automapper

        services.AddAutoMapper();
        .
        .
    }

在另一个名为 xxxMappings 的项目中,我有我的映射配置文件。 示例类

public class StatusMappingProfile : Profile
{
    public StatusMappingProfile()
    {
        CreateMap<Status, StatusDTO>()
         .ForMember(t => t.Id, s => s.MapFrom(d => d.Id))
         .ForMember(t => t.Title, s => s.MapFrom(d => d.Name))
         .ForMember(t => t.Color, s => s.MapFrom(d => d.Color));

    }

    public override string ProfileName
    {
        get { return this.GetType().Name; }
    }
}

并在服务类中以这种方式调用地图

    public StatusDTO GetById(int statusId)
    {
        var status = statusRepository.GetById(statusId);
        return mapper.Map<Status, StatusDTO>(status); //map exception here
    }

status 在调用 statusRepository.GetById 后有值

对于我的 Profile 类,如果不是从 Profile 继承而是从 MapperConfigurationExpression 继承,我会得到一个单元测试,如下所示,表示映射很好。

    [Fact]
    public void TestStatusMapping()
    {
        var mappingProfile = new StatusMappingProfile();

        var config = new MapperConfiguration(mappingProfile);
        var mapper = new AutoMapper.Mapper(config);

        (mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
    }

我的猜测是我的映射没有被初始化。 我该如何检查? 我错过了什么吗? 我看到了 AddAutoMapper() 方法的重载

services.AddAutoMapper(params Assembly[] assemblies)

我应该在我的 xxxMappings 项目中传递所有程序集吗? 我该怎么做?

我想通了。 由于我的映射在不同的项目中,我做了两件事

  1. 从我的 API 项目(Startup.cs 所在的位置,添加了对我的 xxxMaprings 项目的引用)
  2. 在 ConfigureServices 中,我使用了获取程序集的重载 AddAutoMapper:

     public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //register automapper services.AddAutoMapper(Assembly.GetAssembly(typeof(StatusMappingProfile))); //If you have other mapping profiles defined, that profiles will be loaded too.

当我们在解决方案中的不同项目中有映射配置文件时,解决此问题的另一种解决方案是:

services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

1.创建AutoMapperProfile继承Profile类


public class AutoMapperProfile : Profile
{
   public AutoMapperProfile() 
    {
        ConfigureMappings();
    }
    private void ConfigureMappings()
    {
       //  DriverModel and Driver mapping classes
       CreateMap<DriverModel, Driver>().ReverseMap();
    } 
}


2.在配置服务中注册这个配置文件

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(typeof(AutoMapperProfile));
}

暂无
暂无

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

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