首页 > 解决方案 > 带有接口的 Automapper 和自定义值解析器抱怨“类型必须可转换为 IValueResolver...”

问题描述

我目前正在将更大的解决方案迁移到最新的 Automapper 版本(4.2.1 -> 9.0.0)。抽象类ValueResolver已被通用接口取代IValueResolver,现在允许访问源/目标模型,这很棒。我能够毫无问题地迁移一堆我们的自定义价值左轮手枪。到目前为止,一切都很好。

但是我只是不明白为什么编译器在这种特定情况下会抱怨下面的错误消息。由于解析器的签名确实与映射配置文件中给出的约束类型相匹配......

类型“...FooTypeResolver”必须可转换为“Automapper.IValueResolver”,以便在通用方法“void AutoMapper.IMemberConfiguration.MapFrom()”中将其用作参数“TValueResolver”

这是我的个人资料和自定义值解析器。我在这里做错了什么?

public abstract class ABaseMappingProfile<TSrc, TDst> : Profile 
    where TSrc : IProductRelated 
    where TDst : SomeType
{  
    protected AMappingProfile()
    {
        this.CreateMap<TSrc, TDst>()
            // ...
            .ForMember(dest => dest.AStringProperty, opt => opt.MapFrom<FooTypeResolver>())
    }
}

public class FooTypeResolver : IValueResolver<IProductRelated, SomeType, string>
{
    public string Resolve(IProductRelated source, SomeType destination, string destMember, ResolutionContext context)
    {
        //...
    }
}

作为@LucianBargaoanu 评论的附录。以下作品。我仍然不明白为什么上面的尝试没有。

public class AnotherMappingProfile : Profile
{
    public AnotherMappingProfile()
    {
        this.CreateMap<IProductRelated, SomeType>()
            .ForMember(dest => dest.AStringProperty, opt => opt.MapFrom<FooTypeResolver>());
    }
}

将约束TSrcIProductRelated具体类更改为使其工作。然而,在我的情况下,这不是可行的解决方案。

为什么在这种情况下我无法使用界面?

标签: c#automapper

解决方案


推荐阅读