AutoMapper实现自动CreapMap

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

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

解决思路

CreateMap得分两类,80%只是纯创建CreateMap。20%是带自定义映射的。自定义 映射我觉得没必要省了,省个80%也足够了

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

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

那么不妨来个接口定义:

public interface IMapperTo<TDestination>{}

然后同样来个Profile集中处理这些interface

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的话自己扩展咯

  ②这里可以支持多个IMapperTo

所有代码都放在了Gist上了,戳这里代码

posted @ 2016-09-14 16:00  笋干  阅读(1720)  评论(1编辑  收藏  举报
求组队!team扩招中:戳这里