Home > Software engineering >  Using appsettings.json values in Automapper configuration
Using appsettings.json values in Automapper configuration

Time:02-13

Is there a way to get a value from appsettings.json when mapping two objects in Automapper?

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.

CodePudding user response:

From the AutoMapper documentation:

You can’t inject dependencies into Profile classes.

But there are (at least) 2 ways you can achieve what you want:


  1. Using IValueResolver<in TSource, in TDestination, TDestMember> interface.
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. Using IMappingAction<in TSource, in TDestination> implementations.

It is basically an encapsulation of Before and After Map Actions into small reusable classes.

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
     }
}
  • Related