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

17

我正在使用:

  • AutoMapper 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
    }

在调用statusRepository.GetById后,status将具有值。

对于我的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项目中的所有程序集。我该怎么做?

3个回答

18

我明白了。由于我的映射在另一个项目中,所以我做了两件事:

  1. 从我的API项目(其中包含Startup.cs)中,添加了对我的xxxMappings项目的引用。
  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.

6

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

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

1
太棒了!真希望我能给你点赞两次。 - undefined

0

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));
}

这对我没用,它说:“在尝试激活时无法解析类型为'AutoMapper.Mapper'的服务”。配置文件没有被运行。 - liang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接