Error on create instance of custom member resolver in AutoMapper 6

我与影子孤独终老i 提交于 2019-12-11 07:51:02

问题


I'm using AutoMapper 6 (AutoMapper.Extensions.Microsoft.DependencyInjection) for mapping data and view models in a .net core web api application.I have an age property on view model and use custom resolver for calculate age according to birth date come from data model.

This is how i add AutoMapper in StartupClass:

services.AddAutoMapper(config => config.AddProfile(new AutoMapperProfiles()));

And this is AutoMapper profile class:

public class AutoMapperProfiles : Profile
{
    public AutoMapperProfiles()
    {
        CreateMap<User, UserDetailDTO>()
            .ForMember(dest => dest.PhotoUrl, opt =>
            {
                opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url);
            })
        .ForMember(dest => dest.Age, opt =>
        {
            opt.MapFrom<AgeResolverForUserDetail>();
        });

        CreateMap<User, UserListDTO>()
            .ForMember(dest => dest.PhotoUrl, opt =>
            {
                opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url);
            })
        .ForMember(dest => dest.Age, opt =>
        {
            opt.MapFrom<AgeResolverForUserList>();
        });

        CreateMap<Photo, PhotoDTO>();
    }
}

And this is AgeResolverForUserDetail:

public class AgeResolverForUserDetail : IValueResolver<User, UserDetailDTO, int>
{
    public int Resolve(User source, UserDetailDTO destination, int destMember, ResolutionContext context)
    {
        return source.BirthDate.CalculateAge();
    }
}

When i run my app and try to get a user detail, mapping objects throw an exception:

An unhandled exception occurred while processing the request. AutoMapperMappingException: Cannot create an instance of type DatingApp.Utility.AutoMapperUtilities.AgeResolverForUserDetail AutoMapper.MappingOperationOptions.CreateInstance() in MappingOperationOptions.cs, line 47 AutoMapperMappingException: Error mapping types. Mapping types: User -> UserDetailDTO DatingApp.Models.DataModels.User -> DatingApp.Models.ViewModels.UserDetailDTO Type Map configuration: User -> UserDetailDTO DatingApp.Models.DataModels.User -> DatingApp.Models.ViewModels.UserDetailDTO Destination Member: Age

Can you give me a solution for this?

thanks

来源:https://stackoverflow.com/questions/53656777/error-on-create-instance-of-custom-member-resolver-in-automapper-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!