AutoMapper实现自动CreapMap

标题是个噱头,彻底不写代码自动是不现实的,只是简化了CreateMap。方法也是很粗糙的,看看吧。git

我想在使用AutoMapper的时候最恶心的必定是写了一个Profile,里边有n行 Mapper.CreateMap<T1, T2>(),也多是我没有用对?求指教啊~!github

解决思路

CreateMap得分两类,80%只是纯建立CreateMap。20%是带自定义映射的。自定义 映射我以为不必省了,省个80%也足够了app

既然要在初始化的时候解决掉这80%,那么如何加载这些类?如何识别TSource TDestination呢?code

显然配置不能少啊,不管如何TSource/TDestination跑不掉,那么干脆写到TSource上去吧?用什么呢?Attribute?Interface?显然Interface更好处理一些。Attribute看起来会蛋疼一些。blog

那么不妨来个接口定义:接口

public interface IMapperTo<TDestination>{}

而后一样来个Profile集中处理这些interfaceget

typeof(SaveBuyerDemandRequest).Assembly.GetTypes()//①
                .Where(i => i.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IMapperTo<>)))          
                .ToList().ForEach(item =>
                {               
                    item.GetInterfaces()
                        .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IMapperTo<>))
                        .ToList()//②
                        .ForEach(i => {                            
                            var t2 = i.GetGenericArguments()[0];
                            Mapper.CreateMap(item, t2);
                            Mapper.CreateMap(t2, item);
                        });                                                                    
                }); 

  ①:SaveBuyerDemandRequest是TSource同属的Assembly底下的任意类,要包含多个Aeembly的话本身扩展咯it

  ②这里能够支持多个IMapperToio

全部代码都放在了Gist上了,戳这里代码class

相关文章
相关标签/搜索