2020/01/29, ASP.NET Core 3.1, VS2019, AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0html
摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构【8.2-使用AutoMapper映射实体对象】
用依赖注入的方法使用AutoMapper映射git
文章目录github
此分支项目代码后端
本章节介绍了使用AutoMapper映射实体对象的注册部分,用依赖注入的方法使用AutoMapper映射,具体是如何使用的会在下一章节编写业务时作出示范架构
向MS.Models
类库添加包引用:app
<ItemGroup> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" /> </ItemGroup>
这个包是AutoMapper的扩展包,让ASP.NET Core网站能够经过依赖注入的方式使用mapper映射函数
在MS.Models
类库中新建Automapper文件夹,在该文件夹下新建RoleProfile.cs
类:网站
using AutoMapper; using MS.Entities; using MS.Models.ViewModel; namespace MS.Models.Automapper { public class RoleProfile : Profile { public RoleProfile() { CreateMap<RoleViewModel, Role>(); //CreateMap<User, UserData>() // .ForMember(a => a.Id, t => t.MapFrom(b => b.Id)) // .ForMember(a => a.RoleName, t => t.MapFrom(b => b.Role.Name)) // .ForMember(a => a.RoleDisplayName, t => t.MapFrom(b => b.Role.DisplayName)) // .ForMember(a => a.MainDepartmentId, t => t.MapFrom(b => b.UserDepartments.First(x => x.IsMainDepartment == true).Department.Id)) // .ForMember(a => a.MainDepartmentDisplayName, t => t.MapFrom(b => b.UserDepartments.First(x => x.IsMainDepartment == true).Department.GetDisplayName())) // ; } } }
在Automapper文件夹下新建AutomapperServiceExtensions.cs
类:this
using AutoMapper; using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace MS.Models.Automapper { public static class ModelExtensions { /// <summary> /// 注册automapper服务 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddAutomapperService(this IServiceCollection services) { //将AutoMapper映射配置所在的程序集名称注册 services.AddAutoMapper(Assembly.Load(Assembly.GetExecutingAssembly().GetName().Name)); return services; } } }
将AutoMapper映射配置所在的程序集名称注册封装起来spa
在MS.WebApi
应用程序的Startup.cs
类中注册服务:
//using MS.Models.Automapper; //添加以上代码至using //注册automapper服务 services.AddAutomapperService();
完成后以下图所示
至此介绍了使用依赖注入的方式注册Automapper,注册的配置文件也是继承自Profile
使用的时候从构造器中解析出IMapper Mapper 类型便可拿出来用了(具体的使用会在下一篇文章 编写业务时给出)
项目完成后,以下图所示