標題是個噱頭,徹底不寫代碼自動是不現實的,只是簡化了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
②這裏能夠支持多個IMapperTo
io
全部代碼都放在了Gist上了,戳這裏代碼class