具有依赖关系的 Automapper 自定义 ValueResolver

问题描述 投票:0回答:1

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

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-core automapper
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.