C#C
C#2y ago
M B V R K

IValueResolver won't work with AutoMapper

Hi guys , hope all of you doing well,
I'm recently working on a project where I need to convert a special type of values to Datetime as the following example :
public class GetLinkByIdQueryMappingProfile: Profile
{
    public GetLinkByIdQueryMappingProfile()
    {
        CreateMap<GetLinkByIdQuery, GetLinkByIdRequest>();

        CreateMap<GetLinkByIdResponse, GetLinkByIdQueryResultDTO>()
            .ForMember(dest => dest.CreationDateAndTime, opt => opt.MapFrom(src => src.Link.CreationDateAndTime.ToDateTime()))
            .ForMember(dest => dest.ExpirationDateAndTime, opt => opt.MapFrom(src => src.Link.ExpirationDateAndTime.ToDateTime()))
            .ForMember(dest => dest.IsActive, opt => opt.MapFrom(src => src.Link.IsActive));
    }
}

As yiou will notice that many times I will need to manually tell the Automapper how to convert the Google.Protobuf.WellKnownTypes.Timestamp date and time to C# DateTime

So, I read before a bout something called IValueResolver in Automapper, so I created my custom IValueResolver to do this job instead of repteat it like the following :
public class GoogleTimestampToDateTimeValueResolver : IValueResolver<Timestamp, DateTime, DateTime>
{
    public DateTime Resolve(Timestamp source, DateTime destination, DateTime destMember, ResolutionContext context)
    {
        return source.ToDateTime();
    }
}

Bu after using it like the following
            .ForMember(dest => dest.CreationDateAndTime, opt => opt.MapFrom<GoogleTimestampToDateTimeValueResolver>())
            .ForMember(dest => dest.ExpirationDateAndTime, opt => opt.MapFrom<GoogleTimestampToDateTimeValueResolver>())

I got a Compile-Time error saying the message in the attached picture

Please any help to fix this issue ?
Massive thanks in advance <3
image.png
Was this page helpful?