问题
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