[英]Using appsettings.json values in Automapper configuration
在 Automapper 中映射兩個對象時,有沒有辦法從 appsettings.json 獲取值?
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<Employee, EmployeeDto>()
.ForMember(employeeDto => employeeDto.Picture, employee => employee.MapFrom(employee => $"{someValueFromAppSettings}{employee.Picture}"
}
}
我需要 append 在映射圖片名稱之前的路徑,但我似乎無法弄清楚如何以及是否可以使用 Automapper。
來自 AutoMapper 文檔:
您不能將依賴項注入 Profile 類。
但是(至少)有兩種方法可以實現你想要的:
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
}
}
它基本上是將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.