步骤1:项目引用
AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection
步骤2:建立文件 DevProCommonFile
IProfile:是一个空接口,主要用来动态加载文件时查找相关文件,也就时说DevProCommonFile这种文件可以建立多个,只要继承
Profile, IProfile就会被框架加入
using AutoMapper; using Dev.WooNet.Model.DevDTO; using Dev.WooNet.Model.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dev.WooNet.AutoMapper.ProFiles { /// <summary> /// 公共映射文件 /// </summary> public class DevProCommonFile : Profile, IProfile { public DevProCommonFile() { CreateMap<DepartData, DevDepartment>(); //.ForMember(a => a.ContId, opt => opt.Ignore()) //.ForMember(a => a.CreateUserId, opt => opt.Ignore()) //.ForMember(a => a.CreateDateTime, opt => opt.Ignore()) //.ForMember(a => a.ModifyUserId, opt => opt.Ignore()) //.ForMember(a => a.ModifyDateTime, opt => opt.Ignore()); } } }
步骤3:设置加载文件规则
建立Mappings 定一个扩展方法AddDevMapperFiles
using AutoMapper; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Dev.WooNet.AutoMapper.Extend { public static class Mappings { /// <summary> ///映射文件 /// </summary> /// <param name="service"></param> public static void AddDevMapperFiles(this IServiceCollection service) { var allType = Assembly .GetEntryAssembly()//获取默认程序集 .GetReferencedAssemblies()//获取所有引用程序集 .Select(Assembly.Load) .SelectMany(y => y.DefinedTypes) .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType())); service.AddAutoMapper(allType.ToArray()); } } }
步骤4:Startup 的ConfigureServices进行注册
services.AddDevMapperFiles();(上面扩展方法)
步骤5:应用 在控制器注入 IMapper
private IMapper _IMapper { get; set; }
然后 var deptinfo = _IMapper.Map<DevDepartment>(departData);
这样就完成了AutoMapper使用