Automapper error saying mapper is not initialized

I am using Automapper 5.2. I used this link as a basis . I will describe, in stages, the Automapper setup process that I went through.

First I added Automapper to Project.json as indicated:

PM> Install-Package AutoMapper

Second, I created a folder to store all files related to the mapping, called "Mapping"

Third, I installed the Automapper configuration in my own file in the mappings folder:

public class AutoMapperConfiguration
{
    public MapperConfiguration Configure()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<ViewModelToDomainMappingProfile>();
            cfg.AddProfile<DomainToViewModelMappingProfile>();
            cfg.AddProfile<BiDirectionalViewModelDomain>();
        });
        return config;
    }
}

Forth Also, in my own file in the mappings folder, I configured the display profile as follows:

public class DomainToViewModelMappingProfile : Profile
{
    public DomainToViewModelMappingProfile()
    {
        CreateMap<Client, ClientViewModel>()
           .ForMember(vm => vm.Creator, map => map.MapFrom(s => s.Creator.Username))
           .ForMember(vm => vm.Jobs, map => map.MapFrom(s => s.Jobs.Select(a => a.ClientId)));
    }
}

, ... startup.cs:

public static class CustomMvcServiceCollectionExtensions
{
    public static void AddAutoMapper(this IServiceCollection services)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }
        var config = new AutoMapperConfiguration().Configure();
        services.AddSingleton<IMapper>(sp => config.CreateMapper());
    }
}

ConfigureServices Startup.cs

        // Automapper Configuration
        services.AddAutoMapper();

, ...

 IEnumerable<ClientViewModel> _clientVM = Mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);

, , , , , ...

"Mapper . . mapper , , Mapper.Map, ProjectTo UseAsDataSource, , IConfigurationProvider."

.. Automapper? , . .

+13
1

AutoMapper : . , . . .

, mapper , , :

public class FooController : Controller
{
    private readonly IMapper mapper;

    public FooController(IMapper mapper)
    {
        this.mapper = mapper;
    }

:

IEnumerable<ClientViewModel> _clientVM = mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);

AutoMapper :

public MapperConfiguration Configure()
{
    AutoMapper.Mapper.Initialize(cfg =>
    {
        cfg.AddProfile<ViewModelToDomainMappingProfile>();
        cfg.AddProfile<DomainToViewModelMappingProfile>();
        cfg.AddProfile<BiDirectionalViewModelDomain>();
    });
}

Startup.cs; .

+22

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


All Articles