c# - 具有依赖关系的 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>();
但它不起作用。
抛出这个异常我做错了什么?
预先感谢
解决方案
推荐阅读
- javascript - 显示进度条
- sql - 当字段为空时从 SQL 数据透视表中删除行
- json - 如何使用 Django DRF 将“CSV 杂乱数据”转换为“JSON 结构化数据”
- yii2 - Yii2:如何将数据库控制台迁移参数设置为数组
- .net - 为什么 DirectoryEntry.Invoke("SetPassword", value) 触发 Credential Required CryptoAPI Private Key
- c# - 在 C# 中实现部分递归函数
- sql - SQL Server:将表连接到自身以水平显示数据
- c++ - 有没有办法从模板参数和字符串中生成模板类中的类型
- promise - 量角器测试+管理执行顺序
- mysql - 使用 SQL 数据库查询以不同的时间间隔减去相同的列值