.NET Core 中AutoMapper使用配置

1:AutoMapper说明

对象转对象的一种映射器

2:Core中如何配置AutoMapper

1.NuGet安装AutoMapper.Extensions.Microsoft.DependencyInjection

2.创建配置文件,并添加映射配置
需要继承AutoMapper中的Profile,

namespace Pckj.Test.Demo.Services
{
    public class AutoMapperProfiles:Profile
    {
        public AutoMapperProfiles()
        {
            
    //构造函数中创建映射关系 
     CreateMap<Tsourse, TDes>().ReverseMap();  //Tsourse 原对象类型,TDes 目标对象类型  ReverseMap,可相互转换
        }
    }
}

3:在Startup启动类中的ConfigureServices方法中将服务添加到容器

    AutoMapperProfiles是上面步骤中定义的配置文件,具体代码如下:

  services.AddAutoMapper(typeof(AutoMapperProfiles));

其他配置方式如下:

public class Startup
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        /// <summary>
        /// 配置服务
        /// </summary>
        /// <param name="services"></param>
         public void ConfigureServices(IServiceCollection services)
         {
              AutoMapper.MapperConfiguration config = new AutoMapper.MapperConfiguration(mce =>
             {
                 mce.AddMaps(new string[] { "Pckj.Test.Demo.Services" });//添加程序集中包含的映射定义。寻找AutoMapper.Profile 【Pckj.Test.Demo.Services】程序集名称,也就是 AutoMapperProfiles所在的位置)

               //mce.AddProfile(new AutoMapperProfiles()); 
            }); 
       var mapper = config.CreateMapper(); 
        services.AddSingleton<AutoMapper.IMapper>(mapper);
    }
 }

 

使用示例:

 public class DemoService : IDemoService
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper"></param>
        public SupplierService(AutoMapper.IMapper mapper)
        {
            
            Mapper = mapper;
        }
      
        public AutoMapper.IMapper Mapper { get; set; }
     

          Mapper.Map<List<Tdes>>(List<Tsource>) ;//集合转换
          Mapper.Map<Tdes>(Tsource); //对象转换
 }

  

posted on 2020-10-14 15:28  Frank-  阅读(1125)  评论(0编辑  收藏  举报

导航