"存储"使用automapper进行映射时的对象

时间:2017-04-27 12:27:22

标签: c# automapper

让我们说,我们有两种用于映射的源类型和一个目标:

class TSource
{
    public float A { get; set; }
    public float B { get; set; }
}

class TSupport
{
    public float C { get; set; }
    public float D { get; set; }
}

class TDestination
{
    public float A { get; set; }
    public float B { get; set; }
    public float C { get; set; }
    public float D { get; set; }
}

使用TSource实例,使用某种方法获得TSupport的实例:

private TSupport GetSupportInstance(TSource source)

所以,通常,我会用双重映射来做到这一点:

Mapper.CreateMap<TSource, TDestination>();
Mapper.CreateMap<TSupport, TDestination>();
//...
var support = GetSupportInstance(source);

var destination = Mapper.Map<TSource, TDestination>(source);
Mapper.Map(support, destination);

这也可以使用手动解决方案在单一映射中完成:

Mapper.CreateMap<TSource, TDestination>()
    .ForMember(desc => desc.C, opt => opt.ResolveUsing(src =>
    {
        var support = GetSupportInstance(src);
        return support.C;
    }))
    .ForMember(desc => desc.D, opt => opt.ResolveUsing(src =>
    {
        var support = GetSupportInstance(src);
        return support.D;
    }));

正如您所看到的,我为每个属性使用了两次GetSupportInstance。所以,最后,我的问题是 - 是否有可能在映射中获得支持,以某种方式存储它,并在不同属性的映射中重用它?

2 个答案:

答案 0 :(得分:0)

这个怎么样:

Mapper.CreateMap<TSource, TDestination>()
    .ForMember(d => d.C, x => x.Ignore())
    .ForMember(d => d.D, x => x.Ignore())
    .AfterMap((src, dst) => {
        var support = GetSupportInstance(src);
        dst.C = support.C;
        dst.D = support.D;
    });

答案 1 :(得分:0)

我可能会使用一个自定义解析器来缓存你需要的实例。它看起来像这样。

public class MySupportInstanceResolver : ValueResolver<TSource, TDestination> 
{
    private static readonly ISupportInstance _supportInstance;

    [ImportingConstructor]
    public MySupportInstanceResolver ()
    {
      _supportInstance=GetSupportInstance();
    }

    protected override string ResolveCore(Journal source)
    {
        return _supportInstance;
    }
}

然后你可以用它作为:

 cfg.CreateMap<TSource, Tdest>()
        .ForMember(dest => dest.C, 
            opt => opt.ResolveUsing<MySupportInstanceResolver>().FromMember(name => name.C));
});