首页 > 解决方案 > 具有依赖关系的 Automapper 自定义 ValueResolver

问题描述

我正在尝试从数据库模型映射到视图模型。对于一个属性,我需要一个自定义值解析器。

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Model.Db.Kontoauszug, KontoauszugDetailViewModel>()
        .ForMember(dest => dest.IsTeamleiter, opt => opt.MapFrom<KontoauszugIsTeamleiterResolver>());
});

var mapper = new Mapper(config);

return mapper.Map<KontoauszugDetailViewModel>(kontoauszug);

如您在此处看到的,自定义值解析器依赖于服务:

public class KontoauszugIsTeamleiterResolver : IValueResolver<Model.Db.Kontoauszug, KontoauszugDetailViewModel, bool>
{
    private readonly ISysParamService sysParamService;

    public KontoauszugIsTeamleiterResolver(ISysParamService sysParamService)
    {
        this.sysParamService = sysParamService;
    }

    public bool Resolve(Model.Db.Kontoauszug source, KontoauszugDetailViewModel destination, bool destMember, ResolutionContext context)
    {
        var teamleiter = this.sysParamService.GetParamValueAs<string>(KontoauszugSysParamConst.KONTOAUSZUG_TEAMLEITER_MANUMMERN).Split(";").ToList();
        return teamleiter.Contains(source.MitarbeiterNr);
    }
}

不幸的是,在运行此代码时会抛出 valueresolver 没有无参数构造函数的异常。

我正在使用标准的 .net 核心依赖注入,在我的 Startup.cs 中,我正在通过以下方式注册自动映射器

services.AddAutoMapper(typeof(Startup));

我还尝试显式注册值解析器:

services.AddScoped<IValueResolver<Model.Db.Kontoauszug, KontoauszugDetailViewModel, bool>, KontoauszugIsTeamleiterResolver>(); 

但它不起作用。

抛出这个异常我做错了什么?

预先感谢

标签: c#asp.net-core.net-coreautomapper

解决方案


推荐阅读