Automapper Profiles not being loaded in Startup?

2019-06-19 08:26发布

问题:

I'm using:

  • AutoMapper 6.1.1
  • AutoMapper.Extensions.Microsoft.DependencyInjection 3.0.1

It seems my profiles are not being loaded, every time I call the mapper.map I get AutoMapper.AutoMapperMappingException: 'Missing type map configuration or unsupported mapping.'

Here my Startup.cs class ConfigureServices method

 // 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();
        .
        .
    }

In another project called xxxMappings I have my mapping profiles. Example class

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

And call the map this way in a service class

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

status has values after calling statusRepository.GetById

For my Profile classes, if instead of inherit from Profile I inherit from MapperConfigurationExpression I got a unit test like the one below saying the mapping is good.

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

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

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

My guess is that my mappings are not being initialized. How can I check that? Am I missing something? I saw an overload for AddAutoMapper() method

services.AddAutoMapper(params Assembly[] assemblies)

Should I pass all the assemblies in my xxxMappings project. How can I do that?

回答1:

I figure it out. Since my mappings are in a different project, I did two things

  1. From my API project (where Startup.cs is located, added a reference to my xxxMapprings project)
  2. in ConfigureServices I used the overload AddAutoMapper that gets an Assembly:

    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.