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 ...
随机推荐
- Max Sum Plus Plus(最大m字段和,优化)
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Description Now I t ...
- vue2.0 父子组件之间的通信问题
概要: 父组件向子组件通信:props属性 子组件向父组件通信:$emit()触发事件,$on()监听事件 在 vue 1.0 中可以使用$dispatch 和 $broadcast来实现 向上派发事 ...
- 在electron中使用sqlite:sql.js简介
在electron中使用sqlite:sql.js简介 在开发electron应用的时候如果想要使用sqlite3,步骤上除了npm安装以外还要rebuild,比较麻烦.如果你想找一个开箱即用的sql ...
- Redis数据类型,面试相关
1.Redis最为常用的数据类型主要有以下几种 String Hash List (消息队列) Set (可以用于存储不重复的列表数据) Sorted Set (有序不重复数的列表数据) Pub/Su ...
- GetRGB下载
下载地址:https://pan.baidu.com/s/11EyUPa2WxhIgdsTRZtj_eg 07年6-8月做的,用于屏幕取色. 2019年8月30日13点50分
- csp2019 Emiya家今天的饭题解
qwq 由于窝太菜了,实在是不会,所以在题解的帮助下过掉了这道题. 写此博客来整理一下思路 正文 传送 简化一下题意:现在有\(n\)行\(m\)列数,选\(k\)个数的合法方案需满足: 1.一行最多 ...
- Win7、win8、win10下实现精准截获Explorer拷贝行为
介绍了windows下对Explorer的拷贝动作的精确截获,这个在企业数据安全dlp产品系列中减少审计的噪音很有效,方便运营人员做针对性的审计. 在企业数据安全中我通常需要监测用户的拷贝行为,特别像 ...
- C++多重继承实践
实践代码如下: #include <iostream> using namespace std; class Animal { private: int hash; public: Ani ...
- 浏览器端-W3School-JavaScript:JavaScript RegExp 对象
ylbtech-浏览器端-W3School-JavaScript:JavaScript RegExp 对象 1.返回顶部 1. JavaScript RegExp 对象 RegExp 对象 RegEx ...
- iOS多选实现注意点
下面对APP的多选选择列表实现进行总结,为了在以后的每个项目的多选实现,测试总是提一样的bug总结的. 具体的实现代码就不复制粘贴了,不过在多选问题上遇到问题的可以我们一起讨论讨论的哈... 可能总结 ...