将内部映射器添加到 AutoMapper 映射配置文件

Add inner mapper to AutoMapper mapping profile

我正在尝试将源类型的对象映射到目标,它需要一些内部映射。我创建了一个这样的自定义映射器。

public class CustomerMappingProfile : ITypeConverter<Customer, CustomerDTO>
    {
        public CustomerDTO Convert(Customer input, CustomerDTO destination, ResolutionContext context)
        {
            var CustomerDTO = new ObjectMapper<CustomerDTO, Customer>().Apply(input);
            CustomerDTO.NumbOfSeniorYears = input.YearsList != null ? input.YearsList.Count(p => p.Seniority == SeniorityEnum.Senior) : 0;
            CustomerDTO.NumOfYears = input.NumOfYears.Count();
            CustomerDTO.SearchTypeSelection = input.SearchTypeSelection;
            CustomerDTO.UpgradeTypes = input.UpgradeTypes;
            if (input.Rewards.Any())
            {
                foreach (var reward in input.Rewards)
                {
                    var result = Mapper.Map<Customer.Rewards, RewardsDTO>(reward);
                    CustomerDTO.Rewards.Add(result);
                }
            }
            if (input.EliteLevel == -1)
            {
                CustomerDTO.EliteLevel = null;
            }
            else
            {
                CustomerDTO.EliteLevel = input.EliteLevel;
            }
            var softLoggedIn = Helper.Util.PersServicesUtil.GetCharacteristic(input.Characteristics, "SOFT_LOGGED_IN");
            if (softLoggedIn != null)
            {
                if (softLoggedIn.Equals("true"))
                {
                    CustomerDTO.SoftLoginIndicator = true;
                }
                else
                {
                    CustomerDTO.SoftLoginIndicator = false;
                }
            }
            CustomerDTO.SessionId = Customer.SessionId.ToLower();
            return CustomerDTO;
        }


    }

并且我创建了映射配置文件

  public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Rewards, RewardsDTO>();
            CreateMap<Customer, CustomerDTO>().ConvertUsing(new CustomerMappingProfile());;
        }
    }

并将映射配置文件注入 startup.cs

var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingProfile());
            });

            services.AddSingleton(sp => config.CreateMapper());

但我在第 Mapper.Map<Customer.Rewards, RewardsDTO>(reward);

行的自定义映射器中的内部映射出现异常 InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

知道如何添加内部映射吗?

我相信您所有的问题都可以通过编写正确的 AutoMapper 配置来解决。

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Rewards, RewardsDTO>();
        CreateMap<Customer, CustomerDTO>()
            .ForMember(destination => destination.NumbOfSeniorYears, options =>
                options.MapFrom(source => source.YearsList.Count(p => p.Seniority == SeniorityEnum.Senior)))
            .ForMember(destination => destination.NumOfYears, options =>
                options.MapFrom(source => source.NumOfYears.Count()))
            .ForMember(destination => destination.EliteLevel, options =>
                options.Condition(source => source.EliteLevel != -1))
            .ForMember(destination => destination.SoftLoginIndicator, options =>
                options.MapFrom((source, dest, context) =>
                    Helper.Util.PersServicesUtil
                        .GetCharacteristic(source.Characteristics, "SOFT_LOGGED_IN")
                        ?.Equals("true") ?? false))
            .ForMember(destination => destination.SessionId, options =>
                options.MapFrom(source => source.SessionId.ToLower()));
    }
}

从您的代码来看,我认为您混淆了一些东西,例如映射配置文件的概念与类型转换器的概念。您也不必显式映射无论如何都会映射的成员(SearchTypeSelectionUpgradeTypes)。

我强烈建议访问 AutoMapper documentation site,这样您就可以为自己建立扎实的基础知识。有了它,您的映射代码将更高效,编写起来也更短。

还有一件事。恕我直言,您的注入逻辑看起来很奇怪。您是否问过自己是否真的需要 AutoMapper 的自定义单例?为什么不直接调用 AddAutoMapper()?请参阅 documentation 示例,了解如何在 ASP.NET Core 中使用 AutoMapper。