.NetCore学习笔记:四、AutoMapper对象映射

时间:2023-03-09 19:17:22
.NetCore学习笔记:四、AutoMapper对象映射

什么是AutoMapper?
AutoMapper是一个简单的小型库,用于解决一个看似复杂的问题 - 摆脱将一个对象映射到另一个对象的代码。这种类型的代码是相当沉闷和无聊的写,所以为什么不发明一个工具来为我们做?

我们来看看在.netcore3.1中怎样使用AutoMapper9.0。

 public class BasicProfile : Profile, IProfile
{
public BasicProfile()
{
CreateMap<TestDto, Test>();
CreateMap<Test, TestDto>();
}
}

Profile提供了一个命名的映射类,所有继承自Profile类的子类都是一个映射集合。这里我创建了一个BasicProfile继承Profile类。
CreateMap创建映射规则。
IProfile创建影射类的约束,表示继承自该接口的类为映射集合。

由于AutoMapper9.0中取消了自动创建影射规则的方法这里我们需要自己写一个:

 public static class ServiceCollectionExtensions
{
/// <summary>
/// 自动创建映射
/// </summary>
/// <param name="services"></param>
public static void AddAutoMapper(this IServiceCollection services)
{
var allProfile = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Select(Assembly.LoadFrom)
.SelectMany(y => y.DefinedTypes)
.Where(p => p.GetInterfaces().Contains(typeof(IProfile)))
.ToArray();
services.AddAutoMapper(allProfile);
}
}

添加到ConfigureServices:

 public void ConfigureServices(IServiceCollection services)
{
//自动创建映射
services.AddAutoMapper();
}

这样AutoMapper就配置完成,但为了方便调用,我们继续写几个扩展:

 public static class AutoMapperApplicationBuilderExtensions
{
private static IServiceProvider _serviceProvider;
public static void UseStateAutoMapper(this IApplicationBuilder applicationBuilder)
{
_serviceProvider = applicationBuilder.ApplicationServices;
} public static TDestination Map<TDestination>(object source)
{
var mapper = _serviceProvider.GetRequiredService<IMapper>();
return mapper.Map<TDestination>(source);
} public static TDestination Map<TSource, TDestination>(TSource source)
{
var mapper = _serviceProvider.GetRequiredService<IMapper>(); return mapper.Map<TSource, TDestination>(source);
} public static TDestination MapTo<TSource, TDestination>(this TSource source)
{
var mapper = _serviceProvider.GetRequiredService<IMapper>();
return mapper.Map<TSource, TDestination>(source);
} public static TDestination MapTo<TDestination>(this object source)
{
var mapper = _serviceProvider.GetRequiredService<IMapper>();
return mapper.Map<TDestination>(source);
} public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
{
var mapper = _serviceProvider.GetRequiredService<IMapper>();
return mapper.Map<List<TDestination>>(source);
} public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
{
var mapper = _serviceProvider.GetRequiredService<IMapper>();
return mapper.Map<List<TDestination>>(source);
}
}

添加到Configure:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStateAutoMapper();
}

使用:

 public TestDto Get(string id)
{
var test = _testDomain.Get(id);
return test.MapTo<TestDto>();
}

源码地址:https://github.com/letnet/NetCoreDemo