人本善良

导航

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"]));

 

posted on 2019-06-20 17:10  简简单单2018  阅读(335)  评论(0编辑  收藏  举报