AutoMapper 8.0的应用--动态配置

AutoMapper 8.0中,需要使用configure来配置mapper。为此,实现动态的类型配置如下

  public static class AutoMapHelper
    {
        private static bool ConfigExist(Type srcType, Type destType)
        {
            return Mapper.Configuration.FindMapper(new TypePair(srcType, destType)).IsNull();
        }

        private static bool ConfigExist()
        {
            return Mapper.Configuration.FindMapper(new TypePair(typeof(TSrc), typeof(TDest))).IsNull();
        }

        public static T MapTo(this object source)
        {
            if (source.IsNull())
            {
                return default(T);
            }

            if (!ConfigExist(source.GetType(), typeof(T)))
            {
                Mapper.Initialize(cfg => cfg.CreateMap(source.GetType(), typeof(T)));
            }

            return Mapper.Map(source);
        }

        public static IList MapTo(this IEnumerable source)
        {
            foreach (var first in source)
            {
                if (!ConfigExist(first.GetType(), typeof(T)))
                {
                    Mapper.Initialize(cfg => cfg.CreateMap(first.GetType(), typeof(T)));
                }

                break;
            }

            return Mapper.Map>(source);
        }

        public static IList MapTo(this IEnumerable source)
        {
            if (!ConfigExist())
            {
                Mapper.Initialize(cfg => cfg.CreateMap());
            }

            return Mapper.Map>(source);
        }

        public static TDest MapTo(this TSource source, TDest dest)
            where TSource : class
            where TDest : class
        {
            if (source.IsNull())
            {
                return dest;
            }

            if (!ConfigExist())
            {
                Mapper.Initialize(cfg => cfg.CreateMap());
            }

            return Mapper.Map(source);
        }
    }

你可能感兴趣的:(C#开发)