https://www.cnblogs.com/netlock/p/13359173.html
多層架構中存在多種模型,如視圖模型ViewModel,數據傳輸對你DTO,ORM對象等,這些數據在層與層之間進行傳輸必須涉及類型之間的轉換。
AutoMapper是一個對象-對象映射器,作用是通過設置好的映射規則把一個對象轉化為另一個對象,避免每次都去手動寫轉換代碼。
AutoMapper僅是其中一種方式,現在類似的組件多的多,簡單點的自己也可以寫,用順手了哪家都OK。
使用:
1、Nuget引用:
2、ConfigureServices中進行服務注冊(程序集方式):
//添加AutoMapper services.AddAutoMapper(typeof(StartupHelp.MapperProfiles).Assembly);
3、配置映射規則:
public class MapperProfiles : AutoMapper.Profile { public MapperProfiles() { CreateMap<Manager, ManagerModel>().ReverseMap(); } }
4、使用:
public class ManagerService : IManagerService { private readonly IManagerRepository _repository; private readonly IMapper _mapper; public ManagerService(IManagerRepository repository, IMapper mapper) { this._repository = repository; this._mapper = mapper; } public async Task<ManagerModel> GetManagerAsync(string username) { var obj = await _repository.GetManager(username); return _mapper.Map<ManagerModel>(obj); } }
這里用到了構造函數注入,_mapper.Map<ManagerModel>(obj); 一句話即可實現對象之間的轉換。
官方Github地址:https://github.com/AutoMapper/AutoMapper
官方文檔(英文):https://automapper.readthedocs.io/en/latest/Getting-started.html