使用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)); //根据接口类型动态创建代理对象,接口没有实现类 } } }