[英]Using appsettings.json values in Automapper configuration
Is there a way to get a value from appsettings.json when mapping two objects in Automapper?在 Automapper 中映射两个对象时,有没有办法从 appsettings.json 获取值?
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<Employee, EmployeeDto>()
.ForMember(employeeDto => employeeDto.Picture, employee => employee.MapFrom(employee => $"{someValueFromAppSettings}{employee.Picture}"
}
}
I need to append a path before the picture's name on mapping but I can't seem to figure it out how and whether it is even possible with Automapper.我需要 append 在映射图片名称之前的路径,但我似乎无法弄清楚如何以及是否可以使用 Automapper。
From the AutoMapper documentation:来自 AutoMapper 文档:
You can't inject dependencies into Profile classes.您不能将依赖项注入 Profile 类。
But there are (at least) 2 ways you can achieve what you want:但是(至少)有两种方法可以实现你想要的:
public class EmployeeDtoPathResolver: IValueResolver<Employee, EmployeeDto, string>
{
private readonly IConfiguration _configuration
public CarBrandResolver(IConfiguration configuration)
{
_configuration= configuration;
}
public string Resolve(Employee source, EmployeeDto destination, int destMember, ResolutionContext context)
{
var path = // get the required path from _configuration;
return $"{path}{source.Picture}"
}
}
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<Employee, EmployeeDto>()
.ForMember(employeeDto => employeeDto.Picture, opt => opt.MapFrom<EmployeeDtoPathResolver>()); // Edited this
}
}
It is basically an encapsulation of Before
and After
Map Actions into small reusable classes.它基本上是将Before
和After
Map Actions 封装到可重用的小类中。
public class EmployeeDtoAction : IMappingAction<Employee, EmployeeDto>
{
private readonly IConfiguration _configuration;
public EmployeeAction (IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public void Process(Employee source, EmployeeDto destination, ResolutionContext context)
{
var path = // get the required path from _configuration;
destination.Picture = $"{path}{destination.Picture}"
}
}
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<Employee, EmployeeDto>()
.AfterMap<EmployeeDtoAction>(); // Added this
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.