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上了,戳这里代码

  • 相关阅读:
    asp之缓存 cachestate
    ASP。net 之view
    ASP.net gridview之性别
    asp的gridview
    yii源码学习心得2
    yii源码学习心得
    什么是伪静态?伪静态有何作用?
    Yii2.0 时间日期插件之yii2-timepicker
    yii中调整ActiveForm表单样式
    8个新鲜的PHP常用代码
  • 原文地址:https://www.cnblogs.com/capqueen/p/5871237.html
Copyright © 2011-2022 走看看