使用自定义值解析器映射时的解析器生存期

问题描述 投票:0回答:1

我正在使用AutoMapper v9.0.0,我有源对象和目标对象,它们都包含一对多的父/子关系。

调用映射时,将处理〜100k SrcParent对象与<100 SrcChild对象的序列。每个父映射都被单独调用,因此DstParent对象的现有实例可以用DstParent.ConfigurationId值作为种子,MyValueResolver值解析器只能对此数据执行SrcChildDstChild转换。

映射器被添加到asp.net核心di容器中,并且使用services.AddAutoMapper(assemblies, ServiceLifetime.Singleton);覆盖了生存期。

但是,无论指定的生存期如何,映射配置都会为每个孩子实例化一个新的解析器。还有哪些其他选项可以有效地转换父级集合,而子级序列中的每个子实例都需要提示,该提示仅在运行时在目标父级上可用?

public class SrcParent
{
    public int Id { get; set; }
    public List<SrcChild> SrcChildren { get; set; }
}

public class SrcChild
{
    public int Id { get; set; }
    public int SrcParentId { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

public class DstParent
{
    public int Id { get; set; }
    public int ConfigurationId { get; set; }
    public List<DstChild> DstChildren { get; set; }
}

public class DstChild
{
    public int Id { get; set; }
    public int DstParentId { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

this.CreateMap<SrcParent, DstParent>()
    .ForMember(dst => dst.Id, opt => opt.Ignore())
    .ForMember(dst => dst.ConfigurationId, opt => opt.Ignore())
    .ForMember(dst => dst.DstChildren, opt => opt.MapFrom<MyValueResolver>());

public class MyValueResolver : IValueResolver<SrcParent, DstParent, List<DstChild>>
{
    public List<DstChild> Resolve(SrcParent source, DstParent destination, List<DstChild> destMember, ResolutionContext context)
    {
        /*
         * Many expensive operations that can be safely cached
         * on the resolver instance through the lifetime.
         */
    }
}

// Seed the mapper with an existing instance to hint the child conversion.
var dst = new DstParent
{
    ConfigurationId = 42
};

this.mapper.Map(src, dst);

我正在使用AutoMapper v9.0.0,我有源对象和目标对象,它们都包含一对多的父/子关系。调用映射时,约有100k个SrcParent对象的序列,其中<<

c# asp.net-core automapper
1个回答
0
投票
[有一个MapFrom重载,它将一个单例解析器实例作为参数。
© www.soinside.com 2019 - 2024. All rights reserved.