passing around values to an AutoMapper Type Converter from outside

后端 未结 1 455
借酒劲吻你
借酒劲吻你 2021-02-02 13:44

I have a multilingual database, which returns values based on a key and an enum Language. When I convert a DB object to a model, I want the model to contain the tra

相关标签:
1条回答
  • 2021-02-02 14:32

    Just use the Map overload that takes a Action<IMappingOperationOptions>. You can add configuration elements to the Items property that are then passed to your ITypeConverter

    public class CustomConverter : ITypeConverter<string, string>
    {
        public string Convert(ResolutionContext context)
        {
            return "translated in " + context.Options.Items["language"];
        }
    }
    
    internal class Program
    {
        private static void Main(string[] args)
        {
            AutoMapper.Mapper.CreateMap<string, string>().ConvertUsing<CustomConverter>();
            var result = AutoMapper.Mapper.Map<string, string>("value" , opt => opt.Items["language"] = "english");
            Console.Write(result); // prints "translated in english"
            Console.ReadLine();
        }
    }
    
    0 讨论(0)
提交回复
热议问题