什么是 AutoMapper
AutoMapper 是一个对象-对象映射器。对象-对象映射的工作原理是将一种类型的输入对象转换为不同类型的输出对象。AutoMapper 的有趣之处在于,它提供了一些有趣的约定,可以省去如何将类型 A 映射到类型 B 的繁琐工作。只要 B 型遵循 AutoMapper 的既定约定,映射两种类型几乎不需要任何配置。
为什么使用 AutoMapper?
映射代码很无聊。测试映射代码更是无聊。AutoMapper 提供简单的类型配置,以及映射的简单测试。真正的问题可能是“为什么要使用对象-对象映射?映射可以发生在应用程序中的许多位置,但主要发生在层之间的边界中,例如 UI/域层或服务/域层之间。一层的关注点通常与另一层的关注点冲突,因此对象-对象映射会导致隔离模型,其中每一层的关注点只能影响该层中的类型。
安装AutoMapper
使用命令行:Install-Package AutoMapper或者包管理器安装.
定义简单映射类
public class A
{
public string name;
}
public class B : A
{
public string path;
}
public class C
{
public string myName;
}
定义映射配置类
配置类把相关的映射类关连起来,如果属性或字段名称不同将需要指定映射的关系
public class AProfile : Profile
{
public AProfile()
{
CreateMap<A, B>();
CreateMap<A, C>().ForMember(x=> x.myName,option=> option.MapFrom(x=> x.name));
}
}
使用单例模式加载所有映射配置类.
public class Maker
{
static IMapper _mapper;
static IMapper Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<DarwInfoProfile>();
});
return config.CreateMapper();
}
public static IMapper Mapper => _mapper ??= Configure();
}
使用方法
private void ok01_Click(object sender, RoutedEventArgs e)
{
var a = new A();
a.name = "MapNane";
var b = Singleton.Mapper.Map<B>(a);
var c = Singleton.Mapper.Map<C>(a);
}
结果输出:
使用总结
非常简单