.Net Core 6.0 依赖注入的方式使用AutoMapper
AutoMapper是一款单向映射器,是基于对象到对象约定的映射工具,常用于(但并不仅限制于)把复杂的对象模型转为DTO,一般用于ViewModel模式和跨 服务范畴。AutoMapper给用户提供了便捷的配置API,就像使用约定来完成自动映射那样。AutoMapper包含以下功能:平展、投影、配置验证、列表和数组、嵌套映射、自定义类型转换程序、自定义值转换程序 、自定义值格式程序 、Null值替
·
AutoMapper是一款单向映射器,是基于对象到对象约定的映射工具,常用于(但并不仅限制于)把复杂的对象模型转为DTO,一般用于ViewModel模式和跨 服务范畴。
AutoMapper给用户提供了便捷的配置API,就像使用约定来完成自动映射那样。
AutoMapper包含以下功能:平展、投影、配置验证、列表和数组、嵌套映射、自定义类型转换程序、自定义值转换程序 、自定义值格式程序 、Null值替换。
Nuget:AutoMapper
1、入口配置
AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<TradeApiMappingProfile>();
cfg.AddProfile<ServiceMappingProfile>();
});
builder.Services.AddSingleton(config);
builder.Services.AddScoped<IMapper, Mapper>();
2、Profile
//多个配置类,可以在不同的类库下
public class TradeApiMappingProfile: Profile
{
public TradeApiMappingProfile()
{
CreateMap<UserInfoDto, AppUserResponse>();
}
}
public class ServiceMappingProfile: Profile
{
public ServiceMappingProfile()
{
CreateMap<AddUserDto, UserEntity>();
CreateMap<UserEntity, UserInfoDto>();
}
}
3、注入方式使用
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly IMapper _mapper;
public UserController(IUserService userService, IMapper mapper) // IStringLocalizer<Langue> localizer,
{
_userService = userService;
_mapper = mapper;
}
public async Task<ResponseBase<AppUserResponse>> GetUserById(int id)
{
var dto = await _userService.GetUserByIdAsync(id);
var result = new AppUserResponse();
result = _mapper.Map<UserInfoDto, AppUserResponse>(dto);
return new ResponseBase<AppUserResponse>(result);
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)