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 類型便可拿出來用了(具體的使用會在下一篇文章 編寫業務時給出)
項目完成後,以下圖所示