WCF如何使用動(dòng)態(tài)代理精簡(jiǎn)代碼架構(gòu)
使用Castle.Core.dll實(shí)現(xiàn),核心代碼是使用Castle.DynamicProxy.ProxyGenerator類的CreateInterfaceProxyWithoutTarget方法動(dòng)態(tài)創(chuàng)建代理對(duì)象
NuGet上面Castle.Core的下載量1.78億之多
一、重構(gòu)前的項(xiàng)目代碼
重構(gòu)前的項(xiàng)目代碼共7層代碼,其中WCF服務(wù)端3層,WCF接口層1層,客戶端3層,共7層
1.服務(wù)端WCF服務(wù)層SunCreate.InfoPlatform.Server.Service
2.服務(wù)端數(shù)據(jù)庫(kù)訪問(wèn)接口層SunCreate.InfoPlatform.Server.Bussiness
3.服務(wù)端數(shù)據(jù)庫(kù)訪問(wèn)實(shí)現(xiàn)層SunCreate.InfoPlatform.Server.Bussiness.Impl
4.WCF接口層SunCreate.InfoPlatform.Contract
5.客戶端代理層SunCreate.InfoPlatform.Client.Proxy
6.客戶端業(yè)務(wù)接口層SunCreate.InfoPlatform.Client.Bussiness
7.客戶端業(yè)務(wù)實(shí)現(xiàn)層SunCreate.InfoPlatform.Client.Bussiness.Impl
二、客戶端通過(guò)動(dòng)態(tài)代理重構(gòu)
1.實(shí)現(xiàn)在攔截器中添加Ticket、處理異常、Close對(duì)象
2.客戶端不需要再寫代理層代碼,而使用動(dòng)態(tài)代理層
3.對(duì)于簡(jiǎn)單的增刪改查業(yè)務(wù)功能,也不需要再寫業(yè)務(wù)接口層和業(yè)務(wù)實(shí)現(xiàn)層,直接調(diào)用動(dòng)態(tài)代理;對(duì)于復(fù)雜的業(yè)務(wù)功能以及緩存,才需要寫業(yè)務(wù)接口層和業(yè)務(wù)實(shí)現(xiàn)層
客戶端動(dòng)態(tài)代理工廠類ProxyFactory代碼(該代碼目前寫在客戶端業(yè)務(wù)實(shí)現(xiàn)層):
using Castle.DynamicProxy; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace SunCreate.InfoPlatform.Client.Bussiness.Imp { /// <summary> /// WCF服務(wù)工廠 /// PF是ProxyFactory的簡(jiǎn)寫 /// </summary> public class PF { /// <summary> /// 攔截器緩存 /// </summary> private static ConcurrentDictionary<Type, IInterceptor> _interceptors = new ConcurrentDictionary<Type, IInterceptor>(); /// <summary> /// 代理對(duì)象緩存 /// </summary> private static ConcurrentDictionary<Type, object> _objs = new ConcurrentDictionary<Type, object>(); private static ProxyGenerator _proxyGenerator = new ProxyGenerator(); /// <summary> /// 獲取WCF服務(wù) /// </summary> /// <typeparam name="T">WCF接口</typeparam> public static T Get<T>() { Type interfaceType = typeof(T); IInterceptor interceptor = _interceptors.GetOrAdd(interfaceType, type => { string serviceName = interfaceType.Name.Substring(1); //服務(wù)名稱 ChannelFactory<T> channelFactory = new ChannelFactory<T>(serviceName); return new ProxyInterceptor<T>(channelFactory); }); return (T)_objs.GetOrAdd(interfaceType, type => _proxyGenerator.CreateInterfaceProxyWithoutTarget(interfaceType, interceptor)); //根據(jù)接口類型動(dòng)態(tài)創(chuàng)建代理對(duì)象,接口沒(méi)有實(shí)現(xiàn)類 } } }
客戶端攔截器類ProxyInterceptor<T>代碼(該代碼目前寫在客戶端業(yè)務(wù)實(shí)現(xiàn)層):
using Castle.DynamicProxy; using log4net; using SunCreate.Common.Base; using SunCreate.InfoPlatform.Client.Bussiness; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading.Tasks; namespace SunCreate.InfoPlatform.Client.Bussiness.Imp { /// <summary> /// 攔截器 /// </summary> /// <typeparam name="T">接口</typeparam> public class ProxyInterceptor<T> : IInterceptor { private static ILog _log = LogManager.GetLogger(typeof(ProxyInterceptor<T>)); private ChannelFactory<T> _channelFactory; public ProxyInterceptor(ChannelFactory<T> channelFactory) { _channelFactory = channelFactory; } /// <summary> /// 攔截方法 /// </summary> public void Intercept(IInvocation invocation) { //準(zhǔn)備參數(shù) ParameterInfo[] parameterInfoArr = invocation.Method.GetParameters(); object[] valArr = new object[parameterInfoArr.Length]; for (int i = 0; i < parameterInfoArr.Length; i++) { valArr[i] = invocation.GetArgumentValue(i); } //執(zhí)行方法 T server = _channelFactory.CreateChannel(); using (OperationContextScope scope = new OperationContextScope(server as IContextChannel)) { try { HI.Get<ISecurityBussiness>().AddTicket(); invocation.ReturnValue = invocation.Method.Invoke(server, valArr); var value = HI.Get<ISecurityBussiness>().GetValue(); ((IChannel)server).Close(); } catch (Exception ex) { _log.Error("ProxyInterceptor " + typeof(T).Name + " " + invocation.Method.Name + " 異常", ex); ((IChannel)server).Abort(); } } //out和ref參數(shù)處理 for (int i = 0; i < parameterInfoArr.Length; i++) { ParameterInfo paramInfo = parameterInfoArr[i]; if (paramInfo.IsOut || paramInfo.ParameterType.IsByRef) { invocation.SetArgumentValue(i, valArr[i]); } } } } }
如何使用:
List<EscortTask> list = PF.Get<IBussDataService>().GetEscortTaskList();
這里不用再寫try catch,異常在攔截器中處理
三、WCF服務(wù)端通過(guò)動(dòng)態(tài)代理,在攔截器中校驗(yàn)Ticket、處理異常
服務(wù)端動(dòng)態(tài)代理工廠類ProxyFactory代碼(代碼中保存動(dòng)態(tài)代理dll不是必需的):
using Autofac; using Castle.DynamicProxy; using Castle.DynamicProxy.Generators; using SunCreate.Common.Base; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Activation; using System.Text; using System.Threading.Tasks; namespace SunCreate.InfoPlatform.WinService { /// <summary> /// 動(dòng)態(tài)代理工廠 /// </summary> public class ProxyFactory { /// <summary> /// 攔截器緩存 /// </summary> private static ConcurrentDictionary<Type, IInterceptor> _interceptors = new ConcurrentDictionary<Type, IInterceptor>(); /// <summary> /// 代理對(duì)象緩存 /// </summary> private static ConcurrentDictionary<Type, object> _objs = new ConcurrentDictionary<Type, object>(); private static ProxyGenerator _proxyGenerator; private static ModuleScope _scope; private static ProxyGenerationOptions _options; static ProxyFactory() { AttributesToAvoidReplicating.Add(typeof(ServiceContractAttribute)); //動(dòng)態(tài)代理類不繼承接口的ServiceContractAttribute String path = AppDomain.CurrentDomain.BaseDirectory; _scope = new ModuleScope(true, false, ModuleScope.DEFAULT_ASSEMBLY_NAME, Path.Combine(path, ModuleScope.DEFAULT_FILE_NAME), "MyDynamicProxy.Proxies", Path.Combine(path, "MyDymamicProxy.Proxies.dll")); var builder = new DefaultProxyBuilder(_scope); _options = new ProxyGenerationOptions(); //給動(dòng)態(tài)代理類添加AspNetCompatibilityRequirementsAttribute屬性 PropertyInfo proInfoAspNet = typeof(AspNetCompatibilityRequirementsAttribute).GetProperty("RequirementsMode"); CustomAttributeInfo customAttributeInfo = new CustomAttributeInfo(typeof(AspNetCompatibilityRequirementsAttribute).GetConstructor(new Type[0]), new object[0], new PropertyInfo[] { proInfoAspNet }, new object[] { AspNetCompatibilityRequirementsMode.Allowed }); _options.AdditionalAttributes.Add(customAttributeInfo); //給動(dòng)態(tài)代理類添加ServiceBehaviorAttribute屬性 PropertyInfo proInfoInstanceContextMode = typeof(ServiceBehaviorAttribute).GetProperty("InstanceContextMode"); PropertyInfo proInfoConcurrencyMode = typeof(ServiceBehaviorAttribute).GetProperty("ConcurrencyMode"); customAttributeInfo = new CustomAttributeInfo(typeof(ServiceBehaviorAttribute).GetConstructor(new Type[0]), new object[0], new PropertyInfo[] { proInfoInstanceContextMode, proInfoConcurrencyMode }, new object[] { InstanceContextMode.Single, ConcurrencyMode.Multiple }); _options.AdditionalAttributes.Add(customAttributeInfo); _proxyGenerator = new ProxyGenerator(builder); } /// <summary> /// 動(dòng)態(tài)創(chuàng)建代理 /// </summary> public static object CreateProxy(Type contractInterfaceType, Type impInterfaceType) { IInterceptor interceptor = _interceptors.GetOrAdd(impInterfaceType, type => { object _impl = HI.Provider.GetService(impInterfaceType); return new ProxyInterceptor(_impl); }); return _objs.GetOrAdd(contractInterfaceType, type => _proxyGenerator.CreateInterfaceProxyWithoutTarget(contractInterfaceType, _options, interceptor)); //根據(jù)接口類型動(dòng)態(tài)創(chuàng)建代理對(duì)象,接口沒(méi)有實(shí)現(xiàn)類 } /// <summary> /// 保存動(dòng)態(tài)代理dll /// </summary> public static void Save() { string filePath = Path.Combine(_scope.WeakNamedModuleDirectory, _scope.WeakNamedModuleName); if (File.Exists(filePath)) { File.Delete(filePath); } _scope.SaveAssembly(false); } } }
說(shuō)明:object _impl = HI.Provider.GetService(impInterfaceType); 這句代碼用于創(chuàng)建數(shù)據(jù)庫(kù)訪問(wèn)層對(duì)象,HI是項(xiàng)目中的一個(gè)工具類,類似Autofac框架的功能
服務(wù)端攔截器類ProxyInterceptor<T>代碼:
using Castle.DynamicProxy; using log4net; using SunCreate.Common.Base; using SunCreate.InfoPlatform.Server.Bussiness; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading.Tasks; namespace SunCreate.InfoPlatform.WinService { /// <summary> /// 攔截器 /// </summary> public class ProxyInterceptor : IInterceptor { private static ILog _log = LogManager.GetLogger(typeof(ProxyInterceptor)); private object _impl; public ProxyInterceptor(object impl) { _impl = impl; } /// <summary> /// 攔截方法 /// </summary> public void Intercept(IInvocation invocation) { //準(zhǔn)備參數(shù) ParameterInfo[] parameterInfoArr = invocation.Method.GetParameters(); object[] valArr = new object[parameterInfoArr.Length]; for (int i = 0; i < parameterInfoArr.Length; i++) { valArr[i] = invocation.GetArgumentValue(i); } //執(zhí)行方法 try { if (HI.Get<ISecurityImp>().CheckTicket()) { Type implType = _impl.GetType(); MethodInfo methodInfo = implType.GetMethod(invocation.Method.Name); invocation.ReturnValue = methodInfo.Invoke(_impl, valArr); } } catch (Exception ex) { _log.Error("ProxyInterceptor " + invocation.TargetType.Name + " " + invocation.Method.Name + " 異常", ex); } //out和ref參數(shù)處理 for (int i = 0; i < parameterInfoArr.Length; i++) { ParameterInfo paramInfo = parameterInfoArr[i]; if (paramInfo.IsOut || paramInfo.ParameterType.IsByRef) { invocation.SetArgumentValue(i, valArr[i]); } } } } }
服務(wù)端WCF的ServiceHost工廠類:
using Spring.ServiceModel.Activation; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace SunCreate.InfoPlatform.WinService { public class MyServiceHostFactory : ServiceHostFactory { public MyServiceHostFactory() { } public override ServiceHostBase CreateServiceHost(string reference, Uri[] baseAddresses) { Assembly contractAssembly = Assembly.GetAssembly(typeof(SunCreate.InfoPlatform.Contract.IBaseDataService)); Assembly impAssembly = Assembly.GetAssembly(typeof(SunCreate.InfoPlatform.Server.Bussiness.IBaseDataImp)); Type contractInterfaceType = contractAssembly.GetType("SunCreate.InfoPlatform.Contract.I" + reference); Type impInterfaceType = impAssembly.GetType("SunCreate.InfoPlatform.Server.Bussiness.I" + reference.Replace("Service", "Imp")); if (contractInterfaceType != null && impInterfaceType != null) { var proxy = ProxyFactory.CreateProxy(contractInterfaceType, impInterfaceType); ServiceHostBase host = new ServiceHost(proxy, baseAddresses); return host; } else { return null; } } } }
svc文件配置ServiceHost工廠類:
<%@ ServiceHost Language="C#" Debug="true" Service="BaseDataService" Factory="SunCreate.InfoPlatform.WinService.MyServiceHostFactory" %>
如何使用自定義的ServiceHost工廠類啟動(dòng)WCF服務(wù),下面是部分代碼:
MyServiceHostFactory factory = new MyServiceHostFactory(); List<ServiceHostBase> hostList = new List<ServiceHostBase>(); foreach (var oFile in dirInfo.GetFiles()) { try { string strSerName = oFile.Name.Replace(oFile.Extension, ""); string strUrl = string.Format(m_strBaseUrl, m_serverPort, oFile.Name); var host = factory.CreateServiceHost(strSerName, new Uri[] { new Uri(strUrl) }); if (host != null) { hostList.Add(host); } } catch (Exception ex) { Console.WriteLine("出現(xiàn)異常:" + ex.Message); m_log.ErrorFormat(ex.Message + ex.StackTrace); } } ProxyFactory.Save(); foreach (var host in hostList) { try { foreach (var endpoint in host.Description.Endpoints) { endpoint.EndpointBehaviors.Add(new MyEndPointBehavior()); //用于添加消息攔截器、全局異常攔截器 } host.Open(); m_lsHost.TryAdd(host); } catch (Exception ex) { Console.WriteLine("出現(xiàn)異常:" + ex.Message); m_log.ErrorFormat(ex.Message + ex.StackTrace); } }
WCF服務(wù)端再也不用寫Service層了
四、當(dāng)我需要添加一個(gè)WCF接口,以實(shí)現(xiàn)一個(gè)查詢功能,比如查詢所有組織機(jī)構(gòu),重構(gòu)前,我需要在7層添加代碼,然后客戶端調(diào)用,重構(gòu)后,我只需要在3層添加代碼,然后客戶端調(diào)用
1.在WCF接口層添加接口
2.在服務(wù)端數(shù)據(jù)訪問(wèn)接口層添加接口
3.在服務(wù)端數(shù)據(jù)訪問(wèn)實(shí)現(xiàn)層添加實(shí)現(xiàn)方法
4.客戶端調(diào)用:var orgList = PF.Get<IBaseDataService>().GetOrgList();
重構(gòu)前,需要在7層添加代碼,雖然每層代碼都差不多,可以復(fù)制粘貼,但是復(fù)制粘貼也很麻煩啊,重構(gòu)后省事多了,從此再也不怕寫增刪改查了
五、性能損失
主要是invocation.Method.Invoke比直接調(diào)用慢,耗時(shí)是直接調(diào)用的2、3倍,但是多花費(fèi)的時(shí)間跟數(shù)據(jù)庫(kù)查詢耗時(shí)比起來(lái),是微不足道的
以上就是WCF如何使用動(dòng)態(tài)代理精簡(jiǎn)代碼架構(gòu)的詳細(xì)內(nèi)容,更多關(guān)于WCF使用動(dòng)態(tài)代理精簡(jiǎn)代碼架構(gòu)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#使用SQL DataAdapter數(shù)據(jù)適配代碼實(shí)例
今天小編就為大家分享一篇關(guān)于C#使用SQL DataAdapter數(shù)據(jù)適配代碼實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10C#?wpf利用附加屬性實(shí)現(xiàn)界面上定義裝飾器
裝飾器是wpf中可以浮在控件上面的一種組件,我們通常可以用來(lái)實(shí)現(xiàn)一些諸如控件拖動(dòng)點(diǎn)、提示框、自定義鼠標(biāo)等界面功能。本文主要是利用附加屬性實(shí)現(xiàn)界面上定義裝飾器,需要的可以參考下2022-12-12winform使用委托和事件來(lái)完成兩個(gè)窗體之間通信的實(shí)例
這篇文章介紹了winform使用委托和事件來(lái)完成兩個(gè)窗體之間通信的實(shí)例,有需要的朋友可以參考一下2013-09-09在Unity中實(shí)現(xiàn)簡(jiǎn)單的偽時(shí)間同步
這篇文章主要介紹了在Unity中實(shí)現(xiàn)簡(jiǎn)單的偽時(shí)間同步,為什么說(shuō)是偽同步呢,因?yàn)閮H僅是獲取的數(shù)據(jù)庫(kù)所在服務(wù)器的系統(tǒng)時(shí)間,分享給大家,有需要的小伙伴可以參考下2015-03-03C# 表達(dá)式樹Expression Trees的知識(shí)梳理
本篇文章主要介紹了表達(dá)式樹 Expression Trees的基礎(chǔ)知識(shí):Lambda 表達(dá)式創(chuàng)建表達(dá)式樹;API 創(chuàng)建表達(dá)式樹;編譯表達(dá)式樹;執(zhí)行表達(dá)式樹;修改表達(dá)式樹等等,具有一定的參考價(jià)值,下面跟著小編一起來(lái)看下吧2017-01-01