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<TSrc, TDest>()
{
return Mapper.Configuration.FindMapper(new TypePair(typeof(TSrc), typeof(TDest))).IsNull();
}
public static T MapTo<T>(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<T>(source);
}
public static IList<T> MapTo<T>(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<IList<T>>(source);
}
public static IList<TDest> MapTo<TSource, TDest>(this IEnumerable<TSource> source)
{
if (!ConfigExist<TSource, TDest>())
{
Mapper.Initialize(cfg => cfg.CreateMap<TSource, TDest>());
}
return Mapper.Map<IList<TDest>>(source);
}
public static TDest MapTo<TSource, TDest>(this TSource source, TDest dest)
where TSource : class
where TDest : class
{
if (source.IsNull())
{
return dest;
}
if (!ConfigExist<TSource, TDest>())
{
Mapper.Initialize(cfg => cfg.CreateMap<TSource, TDest>());
}
return Mapper.Map<TDest>(source);
}
}