使用Castle.Core.dll实现,核心代码是使用Castle.DynamicProxy.proxygenerator类的CreateInterfaceProxyWithoutTarget方法动态创建代理对象
NuGet上面Castle.Core的下载量1.78亿之多
一、重构前的项目代码
重构前的项目代码共7层代码,其中WCF服务端3层,WCF接口层1层,客户端3层,共7层
1.服务端WCF服务层SunCreate.InfoPlatform.Server.Service
2.服务端数据库访问接口层SunCreate.InfoPlatform.Server.Bussiness
3.服务端数据库访问实现层SunCreate.InfoPlatform.Server.Bussiness.Impl
4.WCF接口层SunCreate.InfoPlatform.Contract
5.客户端代理层SunCreate.InfoPlatform.ClIEnt.Proxy
6.客户端业务接口层SunCreate.InfoPlatform.ClIEnt.Bussiness
7.客户端业务实现层SunCreate.InfoPlatform.ClIEnt.Bussiness.Impl
二、客户端通过动态代理重构
1.实现在拦截器中添加Ticket、处理异常、Close对象
2.客户端不需要再写代理层代码,而使用动态代理层
3.对于简单的增删改查业务功能,也不需要再写业务接口层和业务实现层,直接调用动态代理;对于复杂的业务功能以及缓存,才需要写业务接口层和业务实现层
客户端动态代理工厂类ProxyFactory代码(该代码目前写在客户端业务实现层):
using Castle.DynamicProxy; System; System.Collections.Concurrent; System.Collections.Generic; System.linq; System.ServiceModel; System.Text; System.Threading.Tasks;namespace SunCreate.InfoPlatform.ClIEnt.Bussiness.Imp{ /// <summary> /// WCF服务工厂 PF是ProxyFactory的简写 </summary> public class PF { <summary> 拦截器缓存 </summary> private static ConcurrentDictionary<Type,IInterceptor> _interceptors = new ConcurrentDictionary<Type,IInterceptor>(); 代理对象缓存 object> _obJs = object>(); static proxygenerator _proxygenerator = new proxygenerator(); 获取WCF服务 </summary> <typeparam name="T">WCF接口</typeparam> static T Get<T>() { Type interfaceType = typeof(T); IInterceptor interceptor = _interceptors.GetorAdd(interfaceType,type => { string servicename = interfaceType.name.Substring(1); //服务名称 ChannelFactory<T> channelFactory = new ChannelFactory<T>(servicename); return new ProxyInterceptor<T>(channelFactory); }); return (T)_obJs.GetorAdd(interfaceType,type => _proxygenerator.CreateInterfaceProxyWithoutTarget(interfaceType,interceptor)); 根据接口类型动态创建代理对象,接口没有实现类 } }}VIEw Code
客户端拦截器类ProxyInterceptor<T>代码(该代码目前写在客户端业务实现层):
log4net; SunCreate.Common.Base; SunCreate.InfoPlatform.ClIEnt.Bussiness; System.Reflection; System.ServiceModel.Channels; 拦截器 </summary> 接口</typeparam> class ProxyInterceptor<T> : IInterceptor { static ILog _log = LogManager.GetLogger(typeof(ProxyInterceptor<T>)); private ChannelFactory<T> _channelFactory; public ProxyInterceptor(ChannelFactory<T> channelFactory) { _channelFactory = channelFactory; } 拦截方法 voID Intercept(IInvocation invocation) { 准备参数 ParameterInfo[] parameterInfoArr = invocation.Method.GetParameters(); object[] valArr = new object[parameterInfoArr.Length]; for (int i = 0; i < parameterInfoArr.Length; i++) { valArr[i] = invocation.GetArgumentValue(i); } 执行方法 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参数处理 ) { ParameterInfo paramInfo = parameterInfoArr[i]; if (paramInfo.IsOut || paramInfo.ParameterType.IsByRef) { invocation.SetArgumentValue(i,valArr[i]); } } } }}VIEw Code
如何使用:
List<EscortTask> List = PF.Get<IBussDataService>().GetEscortTaskList();VIEw Code
这里不用再写try catch,异常在拦截器中处理
三、WCF服务端通过动态代理,在拦截器中校验Ticket、处理异常
服务端动态代理工厂类ProxyFactory代码(代码中保存动态代理dll不是必需的):
autofac; Castle.DynamicProxy.Generators; System.IO; System.ServiceModel.Activation; SunCreate.InfoPlatform.WinService{ 动态代理工厂 ProxyFactory { static proxygenerator _proxygenerator; ModuleScope _scope; proxygenerationoptions _options; ProxyFactory() { AttributesToAvoIDReplicating.Add(typeof(ServiceContractAttribute)); 动态代理类不继承接口的ServiceContractAttribute String path = AppDomain.CurrentDomain.BaseDirectory; _scope = new ModuleScope(true,1)">falseMyDynamicProxy.ProxIEsMyDymamicProxy.ProxIEs.dll)); var builder = DefaultProxyBuilder(_scope); _options = proxygenerationoptions(); 给动态代理类添加AspNetCompatibilityRequirementsAttribute属性 PropertyInfo proInfoAspNet = typeof(AspNetCompatibilityRequirementsAttribute).GetProperty(RequirementsMode); CustomAttributeInfo customAttributeInfo = new CustomAttributeInfo(typeof(AspNetCompatibilityRequirementsAttribute).GetConstructor(new Type[0]),1)">object[0],1)">new PropertyInfo[] { proInfoAspNet },1)">[] { AspNetCompatibilityRequirementsMode.Allowed }); _options.AdditionalAttributes.Add(customAttributeInfo); 给动态代理类添加ServiceBehaviorAttribute属性 PropertyInfo proInfoInstanceContextMode = typeof(ServiceBehaviorAttribute).GetProperty(InstanceContextMode); PropertyInfo proInfoConcurrencyMode = ConcurrencyMode); customAttributeInfo = typeof(ServiceBehaviorAttribute).GetConstructor(new PropertyInfo[] { proInfoInstanceContextMode,proInfoConcurrencyMode },1)">[] { InstanceContextMode.Single,ConcurrencyMode.Multiple }); _options.AdditionalAttributes.Add(customAttributeInfo); _proxygenerator = proxygenerator(builder); } 动态创建代理 static CreateProxy(Type contractInterfaceType,Type impInterfaceType) { IInterceptor interceptor = _interceptors.GetorAdd(impInterfaceType,1)">object _impl = HI.ProvIDer.GetService(impInterfaceType); ProxyInterceptor(_impl); }); return _obJs.GetorAdd(contractInterfaceType,type => _proxygenerator.CreateInterfaceProxyWithoutTarget(contractInterfaceType,_options,1)"> } 保存动态代理dll Save() { string filePath = Path.Combine(_scope.WeaknamedModuleDirectory,_scope.WeaknamedModulename); if (file.Exists(filePath)) { file.Delete(filePath); } _scope.SaveAssembly(); } }}VIEw Code
说明:object _impl = HI.ProvIDer.GetService(impInterfaceType); 这句代码用于创建数据库访问层对象,HI是项目中的一个工具类,类似autofac框架的功能
服务端拦截器类ProxyInterceptor<T>代码:
SunCreate.InfoPlatform.Server.Bussiness; ProxyInterceptor : IInterceptor { (ProxyInterceptor)); _impl; public ProxyInterceptor( impl) { _impl = impl; } 执行方法 if (HI.Get<ISecurityImp>().CheckTicket()) { Type impltype = _impl.GetType(); MethodInfo methodInfo = impltype.getmethod(invocation.Method.name); invocation.ReturnValue = methodInfo.Invoke(_impl,valArr); } } (Exception ex) { _log.Error(" + invocation.targettype.name +VIEw Code
服务端WCF的ServiceHost工厂类:
Spring.ServiceModel.Activation; SunCreate.InfoPlatform.WinService{ MyServiceHostFactory : ServiceHostFactory { public MyServiceHostFactory() { } overrIDe ServiceHostBase CreateServiceHost(string reference,Uri[] baseAddresses) { Assembly contractAssembly = Assembly.GetAssembly((SunCreate.InfoPlatform.Contract.IBaseDataService)); Assembly impAssembly = Assembly.GetAssembly((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",Impif (contractInterfaceType != null && impInterfaceType != null) { var proxy = ProxyFactory.CreateProxy(contractInterfaceType,impInterfaceType); ServiceHostBase host = ServiceHost(proxy,baseAddresses); return host; } else; } } }}VIEw Code
svc文件配置ServiceHost工厂类:
<%@ ServiceHost Language="C# DeBUGtrue ServiceBaseDataService FactorySunCreate.InfoPlatform.WinService.MyServiceHostFactory" %>
如何使用自定义的ServiceHost工厂类启动WCF服务,下面是部分代码:
MyServiceHostFactory factory = MyServiceHostFactory();List<ServiceHostBase> hostList = new List<ServiceHostBase>();foreach (var ofile in dirInfo.Getfiles()){ { string strSername = ofile.name.Replace(ofile.Extension,1)">""); string strUrl = .Format(m_strBaseUrl,m_serverPort,ofile.name); var host = factory.CreateServiceHost(strSername,1)">new Uri[] { Uri(strUrl) }); if (host != ) { hostList.Add(host); } } (Exception ex) { Console.Writeline(出现异常: ex.Message); m_log.ErrorFormat(ex.Message + ex.StackTrace); }}ProxyFactory.Save();var host hostList){ var endpoint host.Description.Endpoints) { endpoint.EndpointBehaviors.Add(new MyEndPointBehavior()); 用于添加消息拦截器、全局异常拦截器 } host.open(); m_lsHost.TryAdd(host); } ex.StackTrace); }}VIEw Code
WCF服务端再也不用写Service层了
四、当我需要添加一个WCF接口,以实现一个查询功能,比如查询所有组织机构,重构前,我需要在7层添加代码,然后客户端调用,重构后,我只需要在3层添加代码,然后客户端调用
1.在WCF接口层添加接口
2.在服务端数据访问接口层添加接口
3.在服务端数据访问实现层添加实现方法
4.客户端调用:var orgList = PF.Get<IBaseDataService>().GetorgList();
重构前,需要在7层添加代码,虽然每层代码都差不多,可以复制粘贴,但是复制粘贴也很麻烦啊,重构后省事多了,从此再也不怕写增删改查了
五、性能损失
主要是invocation.Method.Invoke比直接调用慢,耗时是直接调用的2、3倍,但是多花费的时间跟数据库查询耗时比起来,是微不足道的
总结
以上是内存溢出为你收集整理的WCF 使用动态代理精简代码架构 (WCF动态调用)全部内容,希望文章能够帮你解决WCF 使用动态代理精简代码架构 (WCF动态调用)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)