0

So, basically I'm trying to create a TypeConverter to be run in any enumeration mapping. The comments inside the following code explain the problem that I currently have.

  • If I do a map from string to Enum my TypeConverter runs.
  • If I do a map from string to State (a enumeration) my TypeConverter dont run.

The only way that I can run TypeConverter during a specific enumeration mapping is when I create a map for every enumeration inside my namespace (CreateMapForEveryEnum() method). But of course, using reflection is bad for performance and should be avoided.

    using System;
    using System.Linq;
    using System.Reflection;

    using AutoMapper;

    public class Program
    {
        public static void Main(string[] args)
        {
            Mapper.CreateMap<string, Enum>().ConvertUsing<EnumConverter>();

            // call enum converter
            var enumeration1 = Mapper.Map<Enum>("0");
            Console.WriteLine(enumeration1.ToString());

            // dont call enum converter
            var enumeration2 = Mapper.Map<State>("0");
            Console.WriteLine(enumeration2.ToString());

            // create map for every enum inside the current namespace
            CreateMapForEveryEnum();

            // now calls enum converter
            var enumeration3 = Mapper.Map<State>("0");
            Console.WriteLine(enumeration3.ToString());

            Console.ReadLine();
        }

        public enum State
        {
            Active,
            Inactive,
            Idle,
        }

        public enum Test
        {

        }'

        public class EnumConverter : ITypeConverter<string, Enum>
        {
            public Enum Convert(ResolutionContext context)
            {
                return State.Idle;
            }
        }

        private static void CreateMapForEveryEnum()
        {
            const string @namespace = "AutoMapperITypeConverterTest";

            var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsEnum && t.Namespace == @namespace
                    select t;
            q.ToList().ForEach(
                t =>
                {
                    Console.WriteLine("Enum type: " + t.Name);
                    Mapper.CreateMap(typeof(string), t).ConvertUsing<EnumConverter>();
                });
        }
    }
Fagner Carvalho
  • 113
  • 1
  • 1
  • 9

0 Answers0