Automapper profiles not loading in Startup?

I use:

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

My profiles don't seem to load, every time I call mapper.map, I get AutoMapper.AutoMapperMappingException: "There is no type map configuration or unsupported mapping."

Here is my Startup.cs 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. Class example

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 card this way in the service class

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

status matters after calling statusRepository.GetById

For my profile classes, if instead of inheriting from a profile inheriting from MapperConfigurationExpression, I got a unit test, as shown below, that 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();
    }

, . ? - ? AddAutoMapper()

services.AddAutoMapper(params Assembly[] assemblies)

xxxMappings. ?

+4
1

. ,

  • API ( Startup.cs, ​​ xxxMapprings)
  • 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.
    
+4

Source: https://habr.com/ru/post/1685999/


All Articles