.NET的动态编译与WS服务调用详解(3)


 public override int GetHashCode()
  {
      return String.Concat(serviceNamespace, methodAction, methodReplyAction, methodName, returnType).GetHashCode();
  }


然后在WebServiceProxyCreator中加入缓存机制:

复制代码 代码如下:


  public class WebServiceProxyCreator
   {
       private static Dictionary<int, Type> proxyTypeCatch = new Dictionary<int, Type>();

       public Object WebServiceCaller(WebServiceParamaters parameters)
       {
           int key = parameters.GetHashCode();
           Type clientType = null;
           if (proxyTypeCatch.ContainsKey(key))
          {
              clientType = proxyTypeCatch[key];
              Debug.WriteLine("使用缓存");
          }
          else
          {

              CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
              CompilerParameters codeParameters = new CompilerParameters();
              codeParameters.GenerateExecutable = false;
              codeParameters.GenerateInMemory = true;

              StringBuilder code = new StringBuilder();
              CreateProxyCode(code, parameters);

              codeParameters.ReferencedAssemblies.Add("System.dll");
              codeParameters.ReferencedAssemblies.Add("System.ServiceModel.dll");

              CompilerResults results = provider.CompileAssemblyFromSource(codeParameters, code.ToString());
              Assembly assembly = null;
              if (!results.Errors.HasErrors)
              {
                  assembly = results.CompiledAssembly;
              }

              clientType = assembly.GetType("RuntimeServiceClient");

              proxyTypeCatch.Add(key, clientType);
          }
          ConstructorInfo ci = clientType.GetConstructor(new Type[] { typeof(Binding), typeof(EndpointAddress) });
          BasicHttpBinding binding = new BasicHttpBinding(); //只演示传统的WebService调用
          EndpointAddress address = new EndpointAddress(parameters.address);
          Object client = ci.Invoke(new object[] { binding, address });

          MethodInfo mi = clientType.GetMethod(parameters.MethodName);
          Object result = mi.Invoke(client, null);
          mi = clientType.GetMethod("Close"); //关闭代理
          mi.Invoke(client, null);
          return result;
      }

 }

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgdzp.html