使用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;
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服务工厂
/// PF是ProxyFactory的简写
/// </summary>
public class PF
{
/// <summary>
/// 拦截器缓存
/// </summary>
private static ConcurrentDictionary<Type, IInterceptor> _interceptors = new ConcurrentDictionary<Type, IInterceptor>(); /// <summary>
/// 代理对象缓存
/// </summary>
private static ConcurrentDictionary<Type, object> _objs = new ConcurrentDictionary<Type, object>(); private static ProxyGenerator _proxyGenerator = new ProxyGenerator(); /// <summary>
/// 获取WCF服务
/// </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); //服务名称
ChannelFactory<T> channelFactory = new ChannelFactory<T>(serviceName);
return new ProxyInterceptor<T>(channelFactory);
}); return (T)_objs.GetOrAdd(interfaceType, type => _proxyGenerator.CreateInterfaceProxyWithoutTarget(interfaceType, interceptor)); //根据接口类型动态创建代理对象,接口没有实现类
}
}
}

客户端拦截器类ProxyInterceptor<T>代码(该代码目前写在客户端业务实现层):

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)
{
//准备参数
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参数处理
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服务端通过动态代理,在拦截器中校验Ticket、处理异常

服务端动态代理工厂类ProxyFactory代码(代码中保存动态代理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>
/// 动态代理工厂
/// </summary>
public class ProxyFactory
{
/// <summary>
/// 拦截器缓存
/// </summary>
private static ConcurrentDictionary<Type, IInterceptor> _interceptors = new ConcurrentDictionary<Type, IInterceptor>(); /// <summary>
/// 代理对象缓存
/// </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)); //动态代理类不继承接口的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(); //给动态代理类添加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); //给动态代理类添加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>
/// 动态创建代理
/// </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)); //根据接口类型动态创建代理对象,接口没有实现类
} /// <summary>
/// 保存动态代理dll
/// </summary>
public static void Save()
{
string filePath = Path.Combine(_scope.WeakNamedModuleDirectory, _scope.WeakNamedModuleName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_scope.SaveAssembly(false);
}
}
}

说明:object _impl = HI.Provider.GetService(impInterfaceType); 这句代码用于创建数据库访问层对象,HI是项目中的一个工具类,类似Autofac框架的功能

服务端拦截器类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)
{
//准备参数
ParameterInfo[] parameterInfoArr = invocation.Method.GetParameters();
object[] valArr = new object[parameterInfoArr.Length];
for (int i = 0; i < parameterInfoArr.Length; i++)
{
valArr[i] = invocation.GetArgumentValue(i);
} //执行方法
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参数处理
for (int i = 0; i < parameterInfoArr.Length; i++)
{
ParameterInfo paramInfo = parameterInfoArr[i];
if (paramInfo.IsOut || paramInfo.ParameterType.IsByRef)
{
invocation.SetArgumentValue(i, valArr[i]);
}
}
}
}
}

服务端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工厂类启动WCF服务,下面是部分代码:

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("出现异常:" + 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("出现异常:" + ex.Message);
m_log.ErrorFormat(ex.Message + ex.StackTrace);
}
}

WCF服务端再也不用写Service层了

四、当我需要添加一个WCF接口,以实现一个查询功能,比如查询所有组织机构,重构前,我需要在7层添加代码,然后客户端调用,重构后,我只需要在3层添加代码,然后客户端调用

    1.在WCF接口层添加接口

2.在服务端数据访问接口层添加接口

3.在服务端数据访问实现层添加实现方法

4.客户端调用:var orgList = PF.Get<IBaseDataService>().GetOrgList();

重构前,需要在7层添加代码,虽然每层代码都差不多,可以复制粘贴,但是复制粘贴也很麻烦啊,重构后省事多了,从此再也不怕写增删改查了

五、性能损失

主要是invocation.Method.Invoke比直接调用慢,耗时是直接调用的2、3倍,但是多花费的时间跟数据库查询耗时比起来,是微不足道的

六、Demo

https://gitee.com/s0611163/DynamicWCF

https://github.com/0611163/DynamicWCF

WCF 使用动态代理精简代码架构 (WCF动态调用)的更多相关文章

  1. 代理模式(静态代理、JDK动态代理原理分析、CGLIB动态代理)

    代理模式 代理模式是设计模式之一,为一个对象提供一个替身或者占位符以控制对这个对象的访问,它给目标对象提供一个代理对象,由代理对象控制对目标对象的访问. 那么为什么要使用代理模式呢? 1.隔离,客户端 ...

  2. Java动态代理:一个面包店的动态代理帝国

    文章首发于[博客园-陈树义],点击跳转到原文大白话说Java动态代理:一个面包店的动态代理帝国 代理模式是设计模式中非常重要的一种类型,而设计模式又是编程中非常重要的知识点,特别是在业务系统的重构中, ...

  3. TZ_05_Spring_Proxy基于接口的动态代理和基于类的动态代理

    代理:为了增强方法在不添加代码的情况下 1.Proxy基于接口的动态代理 /** * 模拟一个消费者 * @author Administrator * */ public class Client ...

  4. Spring事务Transactional和动态代理(二)-cglib动态代理

    系列文章索引: Spring事务Transactional和动态代理(一)-JDK代理实现 Spring事务Transactional和动态代理(二)-cglib动态代理 Spring事务Transa ...

  5. 设计模式之动态代理(Java的JDK动态代理实现)

    先来看一下思维导图: 对于JDK的动态代理,孔浩老师说学习的方法是把它记下来. 先写一个主题接口类,表示要完成的一个主题. package com.liwei.dynaproxy; /** * 要代理 ...

  6. Java动态代理(三)——Cglib动态代理

    一.Cglib动态代理Cglib是一个优秀的动态代理框架,它的底层使用ASM在内存中动态的生成被代理类的子类,使用Cglib即使代理类没有实现任何接口也可以实现动态代理功能.而且,它的运行速度要远远快 ...

  7. java 27 - 10 反射之 动态代理的代码实现

    为什么要写动态代理类? 例子: 如果现在想做个登陆注册的功能.用户可以执行登陆.注册.添加.删除这些功能. 但是,有些功能是要有一定权限才可以执行的. 而现在已经有了个用户类的接口和该类的实现类了,但 ...

  8. 【Java EE 学习 51】【Spring学习第三天】【cglib动态代理】【AOP和动态代理】【切入点表达式】

    一.cglib动态代理 1.简介 (1)CGlib是一个强大的,高性能,高质量的Code生成类库.它可以在运行期扩展Java类与实现Java接口. (2) 用CGlib生成代理类是目标类的子类. (3 ...

  9. 基于JDK动态代理实现的接口链式调用(Fluent Interface)工具

    什么是链式接口(Fluent Interface) 根据wikipedia上的定义,Fluent interface是一种通过链式调用方法来完成方法的调用,其操作分为终结与中间操作两种.[1] 下面是 ...

  10. Java动态代理(二)CGLIB动态代理应用

    JDK自从1.3版本开始,就引入了动态代理,JDK的动态代理用起来非常简单,但是它有一个限制,就是使用动态代理的对象必须实现一个或多个接口 .如果想代理没有实现接口的类可以使用CGLIB包. CGLI ...

随机推荐

  1. L3-011 直捣黄龙

    #include<bits/stdc++.h> using namespace std; using pii = pair<int, int>; const int N = 3 ...

  2. Python读取Ansible playbooks返回信息

    一.背景及概要设计 当公司管理维护的服务器到达一定规模后,就必然借助远程自动化运维工具,而ansible是其中备选之一.Ansible基于Python开发,集合了众多运维工具(puppet.chef. ...

  3. xv6:labs2 syscall

    lab2 1.lab2的内容总结:关于系统调用整个跟踪过程: 使用系统调用时,用户态会通过软中断(trap,陷阱)进入内核中,由trap识别中断来自系统调用,然后调用syscall函数, 跟踪过程: ...

  4. Vs code创建项目教程

    1.首先,vscode本身没有新建项目的选项,所以要先创建一个空的文件夹. 2.然后打开vscode,再在vscode里面打开文件夹,这样才可以创建项目. 3.选择一个空文件夹. 4.Ctrl+shi ...

  5. Aiganize微信小程序开发手册二代

    根据此表格, 现有三个模块: 活动模块 聊天模块 影子模块 现活动模块交与:赵坤亮.郝文章做 现聊天模块与用户信息交与:葛方杰.陈金鹏做影子模块待定,现做完那两块,已经有不错的用户体验了.

  6. 基于WPSOffice+Pywpsrpc构建Docker镜像,实现文档转换和在线预览服务

    背景 产品功能需要实现标准文档的在线预览功能,由于DOC文档没办法直接通过浏览器打开预览,需要提前转换为PDF文档或者HTML页面. 经过测试发现DOC转为HTML页面后文件提交较大,而且生成的静态资 ...

  7. DC静态时序分析之时钟篇

    DC静态时序分析之时钟篇博主微信:flm13724054952,不懂的有疑惑的也可以加微信咨询,欢迎大家前来投稿,谢谢! 引言介绍在芯片设计或者FPGA设计里面,根据有无时钟,将电路设计分为时序逻辑电 ...

  8. [scrapy]一个简单的scrapy爬虫demo

    一个简单的scrapy爬虫demo 爬取豆瓣top250的电影名称+电影口号 使用到持久化流程: 爬虫文件爬取到数据后,需要将数据封装到items对象中. 使用yield关键字将items对象提交给p ...

  9. bash shell笔记整理——which和whereis命令

    which和whereis命令作用 which:显示给定命令所在路径 whereis:相比which更完善,显示命令路径.man文件路径(如果有).源代码路径 which语法 which [optio ...

  10. Mongo 数据库备份和恢复命令

    转载请注明出处: 在MongoDB中,使用mongodump和mongorestore命令来备份和恢复数据库 mongodump 1.使用方法: 使用 mongodump 命令可以备份MongoDB数 ...