C# AutoMapper展平扩展方法

C# AutoMapper展平扩展方法,c#,automapper,C#,Automapper,我正在寻找利用源对象的扩展方法展平源对象的最简单/最优雅的方法 资料来源: class Source { public int Value1 { get; set; } public int Value2 { get; set; } } 我想优雅地映射的扩展方法: static class SourceExtensions { public static int GetTotal(this Source source) { return sour

我正在寻找利用源对象的扩展方法展平源对象的最简单/最优雅的方法

资料来源:

class Source
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
}
我想优雅地映射的扩展方法:

static class SourceExtensions
{
    public static int GetTotal(this Source source)
    {
        return source.Value1 + source.Value2;
    }
}
目的地:

class Destination
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Total { get; set; }
}
有没有比这更好的方法(我不必调用每个扩展方法)

使用包含MyExtensionMethods的命名空间;
...
Mapper.CreateMap()
.ForMember(destination=>destination.Total,
opt=>opt.resolvesusing(source=>source.GetTotal());
比如:

Mapper.CreateMap<Source, Destination>()
    .ResolveUsingExtensionsInNamespace("NamespaceContainingMyExtensionMethods");
Mapper.CreateMap()
.ResolveUsingExtensionsInNamespace(“包含MyExtensionMethods的命名空间”);
我知道我可以对源对象使用继承继承权,但在我的情况下,这并不理想

我研究过:
并且

添加了提交到我的fork并为此请求拉取。工作起来很有魅力

承诺:

拉取请求:

通过指定要搜索的程序集对其进行配置:

Assembly[] extensionMethodSearch = new Assembly[] { Assembly.Load("Your.Assembly") };
Mapper.Initialize(config => config.SourceExtensionMethodSearch = extensionMethodSearch);
Mapper.CreateMap<Source, Destination>();
Assembly[]extensionMethodSearch=newassembly[]{Assembly.Load(“Your.Assembly”)};
初始化(config=>config.SourceExtensionMethodSearch=extensionMethodSearch);
CreateMap();

粘土材料仍然存在,但随着时间的推移,它已被重构。对于在automapper中搜索此项的用户,您应该使用:

var config = new MapperConfiguration(cfg => {
    cfg.IncludeSourceExtensionMethods(typeof(SourceExtensions));
    cfg.CreateMap<Source, Destination>();
});
var mapper = config.CreateMapper();
var config=new-MapperConfiguration(cfg=>{
IncludeSourceExtensionMethods(typeof(SourceExtensions));
CreateMap();
});
var mapper=config.CreateMapper();

自从在我们的项目中实现这一点以来,我们几次偶然发现了它。我们现在要把它处理掉。有没有听过这样一句话“太聪明了,不自量力”?这就是其中之一。由于AutoMapper在很大程度上是运行时的怪兽,而不是编译时的东西,所以它有可能产生一些潜在的运行时错误。这一特点加剧了这一问题。但希望有一天这对某人有用。
var config = new MapperConfiguration(cfg => {
    cfg.IncludeSourceExtensionMethods(typeof(SourceExtensions));
    cfg.CreateMap<Source, Destination>();
});
var mapper = config.CreateMapper();