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 ...
随机推荐
- cursor url 自定义鼠标样式
cursor可以自定义鼠标,写法是cursor:url(“图片路径”),pointer; url:需使用的自定义光标的 URL.图片类型需要是.cur或.ani和jpg,png等格式的(.cur或.a ...
- 分布式-网络通信-IO-基础(2)
IS 与 OS1. 基本 IO 操作1.1. InputStream 与 OutputStream1.1.1. 输入与输出我们编写的程序除了自身会定义一些数据信息外,经常还会引用外界的数据,或是将自身 ...
- TCP定时器 之 延迟确认定时器
TCP在收到数据段但是无需马上确认时设定,如果在超时时间之内有数据要发送到对端,则确认会随着数据一起发送,即捎带ACK,如果达到超时时间则执行定时器回调立即发送ack: 启动定时器: 延迟确认定时器调 ...
- Spark学习(一)——Spark运行架构
基本概念 在具体讲解Spark运行架构之前,需要先了解几个重要的概念: RDD:是弹性分布式数据集(Resilient Distributed Dataset)的简称,是分布式内存的一个抽象概念,提供 ...
- bootstrap 学习笔记(部分)
这个课程中的boostrap是3.0+版本的.(2.0与3.0有区别) bootstrap中的JS是依赖于jquery的,所以需要事先引用jquery(1.9.0版本以上). <!DOCTYPE ...
- [Flask]通过render_form快捷渲染表单
依赖: Bootstrap-Flask 实例化方式与flask_bootstrap相同. 关于render_form(): Bootstrap-Flask内置了两个用于渲染WTForms表单类的宏,r ...
- [flask]分页显示列表
添加分页支持的视图函数 app.py @app.route('/search') def search(): page = request.args.get('page', 1, type=int) ...
- python开发问题
1. pip3 ''' pip3 install --upgrade pip sudo apt-get install python3-setuptools pip3 install --upgrad ...
- Screen Painter 程序设计
一.Screen 的创建及维护, TCode:SE51 输入程序名称,单击[建立], 程序1000为SAP预留屏幕号,屏幕号必须定义1000外的其他数字,且最多不超过四位, 本例定义屏幕为SAP预留屏 ...
- VMWare中Centos Minimal最小安装包安装后网络,ftp配置
1.官网下载centos Minimal安装包,安装. 2.使用ip addr命令查看后没有ip地址显示. 3.点击WMWare的编辑->虚拟网络编辑->选择vmnet0(Bridged) ...