簡體   English   中英

在 Automapper 配置中使用 appsettings.json 值

[英]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 類。

但是(至少)有兩種方法可以實現你想要的:


  1. 使用IValueResolver<in TSource, in TDestination, TDestMember>接口。
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
     }
}

  1. 使用IMappingAction<in TSource, in TDestination>實現。

它基本上是將BeforeAfter 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM