10.AutoMapper 之自定义值解析器(Custom Value Resolvers)
https://www.jianshu.com/p/3e7cf1d1f17d
自定义值解析器(Custom Value Resolvers)
虽然AutoMapper
涵盖了相当多的目标成员映射方案,但是还是有1%到5%的目标值需要一些帮助才能解析。很多时候,自定义值的解析逻辑是域逻辑,需要直接在我们的作用域上执行解析。但是,如果这些逻辑仅适用于映射操作,则会使我们的源类型混乱并产生不必要的行为。在这种情况下,AutoMapper
允许我们针对目标成员配置自定义值解析器。举个例子,我们可能有一个需要在映射时执行计算的值:
public class Source
{
public int Value1 { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Total { get; set; }
}
我们希望Total为Value1、Value2属性的和。因为某些原因,我们不能将逻辑写在源类型中。这时候我们就需要使用自定义值解析器来满足这个要求。我们首先需要创建一个继承于IValueResolver
的类型:
public interface IValueResolver<in TSource, in TDestination, TDestMember>
{
TDestMember Resolve(TSource source, TDestination destination, TDestMember destMember, ResolutionContext context);
}
ResolutionContext
包含当前解析操作的所有上下文信息,例如源类型,目标类型,源值等。一个实现的例子:
public class CustomResolver : IValueResolver<Source, Destination, int>
{
public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
{
return source.Value1 + source.Value2;
}
}
然后我们就需要告诉AutoMapper
在解析特定目标成员时使用这个自定义值解析器。我们有几种方式来告诉AutoMapper
使用自定义值解析器包括:
- ResolveUsing<TValueResolver>
- ResolveUsing(typeof(CustomValueResolver))
- ResolveUsing(aValueResolverInstance)
在下面的例子当中,我们将使用第一种方式通过泛型来告诉AutoMapper
使用自定义值解析器:
Mapper.Initialize(cfg =>
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>());
Mapper.AssertConfigurationIsValid();
var source = new Source
{
Value1 = 5,
Value2 = 7
};
var result = Mapper.Map<Source, Destination>(source);
result.Total.ShouldEqual(12);
虽然目标成员Total
没有匹配到任何源成员,但自定义解析器已经作为有效的配置,负责为目标成员提供值。
如果我们不关心在值解析器中源/目标的类型,或者希望他们可以跨映射重用,我们可以使用设置源/目标类型为object
:
public class MultBy2Resolver : IValueResolver<object, object, int> {
public int Resolve(object source, object dest, int destMember, ResolutionContext context) {
return destMember * 2;
}
}
自定义构造函数方法
因为我们只向AutoMapper提供了自定义解析器的类型,所以映射引擎将使用反射来创建一个值解析器的实例。
如果我们不想AutoMapper
使用反射创建实例,我们也可以直接提供一个实例:
Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total,
opt => opt.ResolveUsing(new CustomResolver())
);
AutoMapper
将使用该特定的对象,在解析器的构造函数需要参数或者需要由IoC容器创建的情况下非常有用。
给解析器提供定制的源值
AutoMapper
默认会将源对象传给解析器。导致将解析器与源类型耦合,限制了解析器的可重用性。但是,如果我们提供跨多种类型的通用解析器,将重定向后的源值提供给解析器,并使用不同的解析器接口,以便我们的解析器可以使用源/目标成员:
Mapper.Initialize(cfg => {
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total,
opt => opt.ResolveUsing<CustomResolver, decimal>(src => src.SubTotal));
cfg.CreateMap<OtherSource, OtherDest>()
.ForMember(dest => dest.OtherTotal,
opt => opt.ResolveUsing<CustomResolver, decimal>(src => src.OtherSubTotal));
});
public class CustomResolver : IMemberValueResolver<object, object, decimal, decimal> {
public decimal Resolve(object source, object destination, decimal sourceMember, decimal destinationMember, ResolutionContext context) {
// logic here
}
}
将键值传递给Mapper
调用map时,可以使用键值传递额外的对象,并使用自定义解析器从上下文中获取对象。
Mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");
这是如何设置此自定义解析程序的映射
Mapper.CreateMap<Source, Dest>()
.ForMember(d => d.Foo, opt => opt.ResolveUsing((src, dest, destMember, res) => res.Context.Options.Items["Foo"]));
10.AutoMapper 之自定义值解析器(Custom Value Resolvers)的更多相关文章
- 【SpringMVC】SpringMVC系列10之视图与视图解析器
10.视图与视图解析器 10.1.概述 请求处理方法执行完成后,最终返回一个 ModelAndView处理方法,Spring MVC 也会在内部将它们装配成一个ModelAndView 对象, ...
- SpringMVC 自定义参数解析器.
一.简述 有没有想过像 @RequestParam.@RequestBody 这些注解的工作原理呢?为什么 form 表单.application/json 的参数能够直接封装进 Bean 对象中呢? ...
- 自定义Yaml解析器替换Properties文件
自定义Yaml解析器替换Properties文件 项目结构 案例代码 配置类SpringConfiguration @Configuration @Import(JdbcCofnig.class) @ ...
- springmvc 源码分析(三) -- 自定义处理器映射器和自定义处理器适配器,以及自定义参数解析器 和错误跳转自定页面
测试环境搭建: 本次搭建是基于springboot来实现的,代码在码云的链接:https://gitee.com/yangxioahui/thymeleaf.git DispatcherServlet ...
- springMVC源码分析--HandlerMethodReturnValueHandlerComposite返回值解析器集合(二)
在上一篇博客springMVC源码分析--HandlerMethodReturnValueHandler返回值解析器(一)我们介绍了返回值解析器HandlerMethodReturnValueHand ...
- SpringMVC自动封装List对象 —— 自定义参数解析器
前台传递的参数为集合对象时,后台Controller希望用一个List集合接收数据. 原生SpringMVC是不支持,Controller参数定义为List类型时,接收参数会报如下错误: org.sp ...
- SpringBoot系列教程web篇之如何自定义参数解析器
title: 190831-SpringBoot系列教程web篇之如何自定义参数解析器 banner: /spring-blog/imgs/190831/logo.jpg tags: 请求参数 cat ...
- Spring自定义参数解析器
结合redis编写User自定义参数解析器UserArgumentResolver import javax.servlet.http.Cookie; import javax.servlet.htt ...
- Spring 源码(5)BeanFactory使用的准备及自定义属性值解析器
BeanFactory 使用前的准备 上一篇文章 https://www.cnblogs.com/redwinter/p/16165878.html 介绍了自定义标签的使用,完成了AbstractAp ...
随机推荐
- Oracle11g RAC+DG搭建
项目环境准备 3.1虚拟机配置 版本选择 注意Linux操作系统.此次项目我选择的版本是Oracle Enterprise Linux 5.4 内存的设置 本人电脑物理内存8G,由于此次实验要开三台虚 ...
- [CSP-S模拟测试]:最小值(DP+乱搞)
题目背景 $Maxtir$更喜欢序列的最小值. 题目传送门(内部题128) 输入格式 第一行输入一个正整数$n$和四个整数$A,B,C,D$. 第二行输入$n$个整数,第$i$个数表示$a_i$. 输 ...
- oracle判断一个字段为空
比如 insert into table a (a1,b1)values("a1",''); 对于这种情况,因为表里存的是'',其实是没有内容的,要查询这个字段,不能直接使用 se ...
- shell编程连接postgres数据库(数据备份)
第一步:通过xshell或者其他工具连接到linux服务, 第二步:创建一个脚本:touch se.sh 第三步:输入i,代表开始输入内容 输入以下命令: 脚本如下:(sql语句可以是任何复杂的sql ...
- HTML功能框架
起始预定义函数 function $(obj) { return document.getElementById(obj); } 1.用户登陆框架 <!DOCTYPE html> < ...
- weblogic报:java.lang.LinkageError: loader constraint violation in interface itable initialization
原因分析: gdaml服务中依赖org.apache.xerces_2.9.0.v201101211617.jar会产生jar包冲突 解决方法: 项目中的这个jar包删除,并将这个jar包放在服务器中 ...
- setcookie()函数
PHP PDO使用fetchAll()方法获取结果集 fetchAll()方法获取结果集中的所有行数据记录. fetchAll()方法的语法格式如下: array PDOStatement::fetc ...
- 状压dfs小记
一点前(tu)言(cao) 真的考起dfs来可谓是什么都能往dfs上套 状压不止能dp,还能与dfs结合成为搜索好(duliu)题 剪枝卡常司空见惯(打开题解一看并不是纯dfs,emmmm) 开始正文 ...
- P1533可怜的狗狗
困死了,完全做不下去题 就当是对莫队最最基本的思想的一个复习叭(只有最最基本的思想,没有莫队) 传送 我们可以很容易的想到这题要用线段树. 60pts 此题要求某个区间里第K小的数,可以暴力的考虑对每 ...
- Jenkins持续集成环境部署
一.下载Jenkins Jenkins下载地址:https://jenkins.io/download/ 这里我们下载的是jenkins.war 二.启动Jenkins 在Linux下启动Jenkin ...