1:首先还是需要直接Nutget两个包:
准备两个数据类
public class Person { public string Name { get; set; } } public class PersonDto { public string Name { get; set; } }
2、通用注册:
Register为了方便扩展,不需要再去service里添加每一个Type
1.先创建一个Iprofile 接口
public Interface Iprofile { }
2.profile配置类继承这个接口
public class PersonProfile:Profile,Iprofile { public PersonProfile { CreateMap<Person,PersonDto>(); CreateMap<PersonDto,Person>() ; } }
3.创建一个MapperRegister类
public static class MapperRegister { public static Type[] MapType() { var allIem = Assembly .GetEntryAssembly() .GetReferencedAssemblies() .Select(Assembly.Load) .SelectMany(y => y.DefinedTypes) .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType())); List<Type> allList = new List<Type>(); foreach (var typeinfo in allIem) { var type = typeinfo.AsType(); allList.Add(type); } Type[] alltypes = allList.ToArray(); return alltypes; } }
4.更改 StartUp.cs->AddAutoMapper
public void ConfigureServices(IServiceCollection services) { services.AddAutoMapper(MapperRegister.MapType); }
所以继承IProfile的配置类都会被自动注册到AutoMapper里
2、通用的方法:AutoMapperHelper
此处AutoMapperHelper有两个意义,一,不需要在每个调用mapper方法的类里再去调用IMapper,由Helper 统一调用一次。二,映射实现的写法更易读(二处的意义现在不太大,9.0之前的Helper方法可以节约三行代码,但9.0更新之后,现在原生的mapper也只需要一行代码)
public static class AutoMapperHelper { 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); } }
在 Startup.cs 配置一下
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { .... app.UseStateAutoMapper(); }
使用
public PersonDto Get() { ... PersonDto dto=Person.MapTo<PersonDto>(); return dto; } //集合 public List<PersonDto> GetList() { ... List<PersonDto> dtoList=Personlist.MapToList<PersonDto>(); return dtoList; }