WCF如何使用 * 精简代码架构

作者:firebet 时间:2023-09-17 16:25:42 

使用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倍,但是多花费的时间跟数据库查询耗时比起来,是微不足道的

来源:https://www.cnblogs.com/firebet/p/14513991.html

标签:wcf, , ,c#
0
投稿

猜你喜欢

  • C# 中AutoMapper的使用方法

    2023-04-06 13:17:04
  • Android实现取消GridView中Item选中时默认的背景色

    2023-02-26 05:53:30
  • Spring Cloud 的 Hystrix.功能及实践详解

    2023-11-19 06:40:46
  • springboot解决java.lang.ArrayStoreException异常

    2023-06-24 19:22:25
  • VS2019配置opencv详细图文教程和测试代码的实现

    2023-07-17 13:49:31
  • SpringBoot项目鉴权的4种方式小结

    2021-10-23 20:10:05
  • spring boot如何使用AOP统一处理web请求

    2023-05-16 14:15:11
  • C#中的多线程多参数传递详解

    2023-08-02 22:23:46
  • Android 中对于图片的内存优化方法

    2023-11-23 12:24:41
  • spring解决循环依赖的方案示例

    2021-11-19 03:31:04
  • Android实现使用微信登录第三方APP的方法

    2021-06-09 00:05:02
  • SpringBoot项目没有把依赖的jar包一起打包的问题解决

    2021-08-11 12:15:02
  • C#常用日期时间方法汇总

    2023-01-04 23:44:55
  • Java线程优先级和守护线程原理解析

    2023-03-27 16:45:30
  • Java实现XML文件学生通讯录

    2023-07-23 19:21:49
  • Java 深入探讨设计模式之原型模式篇

    2023-11-16 17:37:59
  • C#导出文本内容到word文档的方法

    2021-10-15 19:00:37
  • Android onCreate( )方法详细介绍

    2023-02-24 12:27:07
  • AndroidStudio插件GsonFormat之Json快速转换JavaBean教程

    2021-10-10 12:48:05
  • Android读写文件工具类详解

    2021-10-08 18:08:12
  • asp之家 软件编程 m.aspxhome.com