什么是AutoMapper?
AutoMapper是一个简单的小型库,用于解决一个看似复杂的问题 - 摆脱将一个对象映射到另一个对象的代码。这种类型的代码是相当沉闷和无聊的写,所以为什么不发明一个工具来为我们做?
我们来看看在.netcore3.1中怎样使用AutoMapper9.0。
1 public class BasicProfile : Profile, IProfile 2 { 3 public BasicProfile() 4 { 5 CreateMap<TestDto, Test>(); 6 CreateMap<Test, TestDto>(); 7 } 8 }
Profile提供了一个命名的映射类,所有继承自Profile类的子类都是一个映射集合。这里我创建了一个BasicProfile继承Profile类。
CreateMap创建映射规则。
IProfile创建影射类的约束,表示继承自该接口的类为映射集合。
由于AutoMapper9.0中取消了自动创建影射规则的方法这里我们需要自己写一个:
1 public static class ServiceCollectionExtensions 2 { 3 /// <summary> 4 /// 自动创建映射 5 /// </summary> 6 /// <param name="services"></param> 7 public static void AddAutoMapper(this IServiceCollection services) 8 { 9 var allProfile = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Select(Assembly.LoadFrom) 10 .SelectMany(y => y.DefinedTypes) 11 .Where(p => p.GetInterfaces().Contains(typeof(IProfile))) 12 .ToArray(); 13 services.AddAutoMapper(allProfile); 14 } 15 }
添加到ConfigureServices:
1 public void ConfigureServices(IServiceCollection services) 2 { 3 //自动创建映射 4 services.AddAutoMapper(); 5 }
这样AutoMapper就配置完成,但为了方便调用,我们继续写几个扩展:
1 public static class AutoMapperApplicationBuilderExtensions 2 { 3 private static IServiceProvider _serviceProvider; 4 public static void UseStateAutoMapper(this IApplicationBuilder applicationBuilder) 5 { 6 _serviceProvider = applicationBuilder.ApplicationServices; 7 } 8 9 public static TDestination Map<TDestination>(object source) 10 { 11 var mapper = _serviceProvider.GetRequiredService<IMapper>(); 12 return mapper.Map<TDestination>(source); 13 } 14 15 public static TDestination Map<TSource, TDestination>(TSource source) 16 { 17 var mapper = _serviceProvider.GetRequiredService<IMapper>(); 18 19 return mapper.Map<TSource, TDestination>(source); 20 } 21 22 public static TDestination MapTo<TSource, TDestination>(this TSource source) 23 { 24 var mapper = _serviceProvider.GetRequiredService<IMapper>(); 25 return mapper.Map<TSource, TDestination>(source); 26 } 27 28 public static TDestination MapTo<TDestination>(this object source) 29 { 30 var mapper = _serviceProvider.GetRequiredService<IMapper>(); 31 return mapper.Map<TDestination>(source); 32 } 33 34 public static List<TDestination> MapToList<TDestination>(this IEnumerable source) 35 { 36 var mapper = _serviceProvider.GetRequiredService<IMapper>(); 37 return mapper.Map<List<TDestination>>(source); 38 } 39 40 public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source) 41 { 42 var mapper = _serviceProvider.GetRequiredService<IMapper>(); 43 return mapper.Map<List<TDestination>>(source); 44 } 45 }
添加到Configure:
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 2 { 3 app.UseStateAutoMapper(); 4 }