automapper 10 +autofac+asp.net web api
automapper 不必多说 https://automapper.org
autofac 这里也不多说 https://autofac.org
这里主要 说 automapper 10.0 版本+autofac 在asp.net web api 的简单使用,因为automapper 更新很快每个版本的差别很大 ,网上查找的资料也比较杂而乱,找了好半天也找不出个好的
也没写过啥博文直接上干货
1.vs nuget 中搜索 automapper 安装
2.在项目中添加 此类 记得集成 Profile
public class MappingProfile : Profile { public MappingProfile() {//此处是类与类的映射.... 这里就简单的举例一个
CreateMap<Core.Model.PO.admin, Models.Default.Admin>();
}
}
3.在autofac 中 注册 automapper
public static void Register() { //得到你的HttpConfiguration. var configuration = GlobalConfiguration.Configuration; var builder = new ContainerBuilder(); //注册所有api控制器 构造函数注入 builder.RegisterApiControllers(Assembly.GetCallingAssembly()); // 注册auto mapper var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile<MappingProfile>();//添加MappingProfile 实现映射的类 }); IMapper mapper = mapperConfiguration.CreateMapper(); builder.RegisterInstance(mapper).As<IMapper>().SingleInstance(); ...... 此处省去代码 100行 }
4.在控制器构造函数中 使用 IMapper
public class DefaultController : ApiController { private readonly IMapper _mapper; private readonly IAdminService _adminService; public DefaultController(IMapper mapper, IAdminService adminService) { _mapper = mapper; _adminService = adminService; } [HttpGet,Filter.CustomActionFilter] public IHttpActionResult user() { List<Core.Model.PO.admin> list = _adminService.GetList(); var customers = _mapper.Map<List<Admin>>(list); return Ok(new {code=0 ,data=customers }); } }