AutoMapper之自定义解析

自定义解析

4.自定义解析

AutoMapper可以通过名称匹配等规则进行对象的映射,但是在实际的项目中,只是这样是远远不够的,比说我们需要名称不同的字段进行映射,或者需要再加一些逻辑处理。AutoMapper为此提供一种方案:自定义解析。

4.1示例

我们先对类Source中Value1和Value2进行求和运算,再映射到类Destination中Total。

public class Source
{
	public int Value1 { get; set; }
	public int Value2 { get; set; }
}

public class Destination
{
	public int Total { get; set; }
}

AutoMapper提供了接口IValueResolver实现自定义解析,其中包含有源类型,源对象,目标类型,目标对象等信息。

//IValueResolver接口
public interface IValueResolver<in TSource, in TDestination, TDestMember>
{
	TDestMember Resolve(TSource source, TDestination destination, TDestMember destMember, ResolutionContext context);
}

在这里我们需要继承这个接口,就可以实现自定义解析。

//继承接口IValueResolver 
/// <summary>
/// 自定义解析类
/// </summary>
public class CustomResolver : IValueResolver<Source, Destination, int>
{
    /// <summary>
    /// 自定义解析实现
    /// </summary>
    /// <param name="source">源对象</param>
    /// <param name="destination">目标对象</param>
    /// <param name="member"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
    {
    //逻辑处理 对Value1和Value2进行求和运算
        return source.Value1 + source.Value2;
    }
}

//测试方法
[TestMethod]
public void CustomValResTest()
{
	//初始化映射规则,并调用 CustomResolver自定义解析
    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);

    Assert.AreEqual(12,result.Total);  //测试通过
}

4.2根据源映射值解析

上一个示例中我们把源对象和目标对象当成参数传入,这样就降低了方法的重用性。我们可以把源对象和目标对象用Object代替,传入源对象的映射源值,这样可以对映射源值进行逻辑处理。

//继承接口 IMemberValueResolver
/// <summary>
/// 自定义解析类V2 根据源对象的源映射值解析
/// </summary>
public class CustomResolverV2 : IMemberValueResolver<object, object, int, int>
{
    public int Resolve(object source, object destination, int sourceMember, int destinationMember, ResolutionContext context)
    {
		// logic here
        return sourceMember * 2;            
    }
}

//测试方法
[TestMethod]
public void CustomValResV2Test()
{
    //初始化映射规则,
    Mapper.Initialize(cfg =>
    cfg.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolverV2,int>(src=>src.Value1)));
    //Mapper.AssertConfigurationIsValid();
    var source = new Source
    {
        Value1 = 5,
        //Value2 = 7
    };
    var result = Mapper.Map<Source, Destination>(source);
    Assert.AreEqual(10, result.Total); //测试通过
}
posted @ 2017-04-03 16:09  山中自有人  阅读(2327)  评论(0编辑  收藏  举报