zoukankan      html  css  js  c++  java
  • 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上了,戳这里代码

  • 相关阅读:
    现代操作系统-读者/写者问题
    现代操作系统-进程互斥
    关于网页强制被跳转到wpkg.org的解决
    Leetcode Count Prime
    Leetcode Add Two Numbers
    Leetcode Two Sum
    can't find -lsocket的解决办法
    删除Windows右键不用的选项
    Linux下的另一个词典GoldenDict
    spark执行例子eclipse maven打包jar
  • 原文地址:https://www.cnblogs.com/capqueen/p/5871237.html
Copyright © 2011-2022 走看看