服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - WCF如何使用动态代理精简代码架构

WCF如何使用动态代理精简代码架构

2022-11-07 13:20firebet C#

这篇文章主要介绍了WCF如何使用动态代理精简代码架构,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

使用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代码(该代码目前写在客户端业务实现层):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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>代码(该代码目前写在客户端业务实现层):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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]);
  }
  }
 }
 }
}

如何使用:

?
1
List<EscortTask> list = PF.Get<IBussDataService>().GetEscortTaskList();

这里不用再写try catch,异常在拦截器中处理

三、WCF服务端通过动态代理,在拦截器中校验Ticket、处理异常

服务端动态代理工厂类ProxyFactory代码(代码中保存动态代理dll不是必需的):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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>代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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工厂类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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工厂类:

?
1
<%@ ServiceHost Language="C#" Debug="true" Service="BaseDataService" Factory="SunCreate.InfoPlatform.WinService.MyServiceHostFactory" %>

如何使用自定义的ServiceHost工厂类启动WCF服务,下面是部分代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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倍,但是多花费的时间跟数据库查询耗时比起来,是微不足道的

以上就是WCF如何使用动态代理精简代码架构的详细内容,更多关于WCF使用动态代理精简代码架构的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/firebet/p/14513991.html

延伸 · 阅读

精彩推荐
  • C#C#正方形图片的绘制方法

    C#正方形图片的绘制方法

    这篇文章主要为大家详细介绍了C#正方形图片的绘制方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    薛定谔家的猫12212022-03-02
  • C#C# 读写XML(代码分享)

    C# 读写XML(代码分享)

    本文主要介绍了C# 读写XML的相关知识,具有很好的参考价值。下面跟着小编一起来看下吧...

    X.S5042021-12-29
  • C#C#实现餐饮管理系统完整版

    C#实现餐饮管理系统完整版

    这篇文章主要为大家详细介绍了C#实现餐饮管理系统的完整版,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    战歌IT6462022-03-09
  • C#C#控件picturebox实现图像拖拽和缩放

    C#控件picturebox实现图像拖拽和缩放

    这篇文章主要为大家详细介绍了C#控件picturebox实现图像拖拽和缩放,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    zyz22339182022-03-01
  • C#详解C#对路径...的访问被拒绝解决过程

    详解C#对路径...的访问被拒绝解决过程

    这篇文章主要介绍了详解C#对路径...的访问被拒绝解决过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    Mr.Emiya5592022-10-25
  • C#C#实现泛型List分组输出元素的方法

    C#实现泛型List分组输出元素的方法

    这篇文章主要介绍了C#实现泛型List分组输出元素的方法,涉及C#针对List的遍历、排序、输出等相关操作技巧,需要的朋友可以参考下...

    SharpL7142022-02-13
  • C#C#实现基于加减按钮形式控制系统音量及静音的方法

    C#实现基于加减按钮形式控制系统音量及静音的方法

    这篇文章主要介绍了C#实现基于加减按钮形式控制系统音量及静音的方法,涉及C#引用user32.dll动态链接库操作系统音量的相关技巧,具有一定参考借鉴价值,需...

    小编辑9982021-10-28
  • C#C# GroupBy的基本使用教程

    C# GroupBy的基本使用教程

    这篇文章主要给大家介绍了关于C# GroupBy的基本使用教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    weilence11162022-03-09