WebService帮助类改良版,支持多webservice

帮助类代码

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web.Services.Description;
using System.Xml;
using System.Xml.Serialization;

namespace PTool.WebService
{
    public class WSCollectionHelper
    {
        private static object _obj = new object();
        private static WSCollectionHelper _ws = null;
        private Dictionary<string,object> _wsClassInstanceList = null;
        private Type _wsClassType = null;
        private  List<WSCollectionModel> _paramcollection = null;
        public  string xmlurl = string.Empty;

        private bool _lastConn = true;
        #region 事件
        public event Action<bool> WsConnectionHandle;
        #endregion

        #region 单一实例
        private WSCollectionHelper()
        {
            xmlurl = ConfigurationManager.AppSettings["XmlUrl"].ToString();
            if (_paramcollection == null)
            {
                CreateXml();
            }
        }

        private  void CreateParaCollectionList(XmlNodeList nodelist)
        {
            if (nodelist != null)
            {
                if (_paramcollection == null)
                {
                    _paramcollection = new List<WSCollectionModel>();
                }
                foreach (XmlNode item in nodelist)
                {
                    WSCollectionModel model = new WSCollectionModel();
                    if (!DBConvert.IsDBNull(item.Attributes["FunctionName"]))
                    {
                        model.Function_name = DBConvert.ToString(item.Attributes["FunctionName"].InnerText);
                    }
                    if (!DBConvert.IsDBNull(item.Attributes["ClassName"]))
                    {
                        model.Class_name = DBConvert.ToString(item.Attributes["ClassName"].InnerText);
                    }
                    if (!DBConvert.IsDBNull(item.Attributes["NameSpace"]))
                    {
                        model.Name_space = DBConvert.ToString(item.Attributes["NameSpace"].InnerText);
                    }
                    if (!DBConvert.IsDBNull(item.Attributes["WsUrl"]))
                    {
                        model.Ws_url = DBConvert.ToString(item.Attributes["WsUrl"].InnerText);
                    }
                    _paramcollection.Add(model);
                }

            }

        }

        /// <summary>
        /// 获取当前实例
        /// </summary>
        public static WSCollectionHelper CurrentInstance
        {
            get
            {
                if (_ws == null)
                {
                    lock (_obj)
                    {
                        if (_ws == null)
                        {
                            _ws = new WSCollectionHelper();
                        }
                    }
                }
                return _ws;
            }
        }
        #endregion

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public object GetData(string methodName, object[] param)
        {
            try
            {
                 object item = null;
                if (_wsClassInstanceList == null)
                {
                    _wsClassInstanceList = new Dictionary<string, object>();
                }
                WSCollectionModel selectmodel=_paramcollection.Find(x => x.Function_name == methodName);
                if (selectmodel != null)
                {
                    object _wsClassInstance = null;
                    if (!_wsClassInstanceList.ContainsKey(selectmodel.Ws_url))
                    {
                        _wsClassInstance = CreateClassInstance(selectmodel.Ws_url, selectmodel.Class_name);
                        _wsClassInstanceList.Add(selectmodel.Ws_url, _wsClassInstance);
                    }
                    else
                    {
                        _wsClassInstance = _wsClassInstanceList[selectmodel.Ws_url];
                    }
                    System.Reflection.MethodInfo method = _wsClassType.GetMethod(methodName);
                    item = method.Invoke(_wsClassInstance, param);
                    if (_lastConn != true && null != WsConnectionHandle)
                    {
                        _lastConn = true;
                        WsConnectionHandle.BeginInvoke(false, null, null);
                    }
                }
                return item;
            }
            catch (Exception e)
            {
                if (_lastConn != false && null != WsConnectionHandle)
                {
                    _lastConn = false;
                    WsConnectionHandle.BeginInvoke(false, null, null);
                }

                return null;
            } 
        }

        public  void CreateXml()
        {
            XMLFileHelper xml = new XMLFileHelper(xmlurl);
            XmlNodeList nodelist = xml.GetNodeList("root/wsmodel");
            CreateParaCollectionList(nodelist);
        }

        private object CreateClassInstance(string url,string classname)
        {
            try
            {
                object _wsClassInstance = null;
                // 1. 使用 WebClient 下载 WSDL 信息。
                WebClient web = new WebClient();
             
                Stream stream = web.OpenRead(url);
                // 2. 创建和格式化 WSDL 文档。
                ServiceDescription description = ServiceDescription.Read(stream);
                // 3. 创建客户端代理代理类。
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                // 指定访问协议。
                importer.ProtocolName = "Soap";
         
                // 生成客户端代理。
                importer.Style = ServiceDescriptionImportStyle.Client;
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                // 添加 WSDL 文档。
                importer.AddServiceDescription(description, null, null);
                // 4. 使用 CodeDom 编译客户端代理类。
                // 为代理类添加命名空间,缺省为全局空间。
                CodeNamespace nmspace = new CodeNamespace(); 
                CodeCompileUnit unit = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);

                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
             
                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                parameter.GenerateInMemory = true;
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");
              
                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

                if (!result.Errors.HasErrors)
                {
                    Assembly asm = result.CompiledAssembly;
                    _wsClassType = asm.GetType(classname);
                   _wsClassInstance = Activator.CreateInstance(_wsClassType);
                }
                return _wsClassInstance;
            }
            catch (Exception e)
            {
                //_wsClassInstance = null;
                //_wsClassType = null;
                throw e;
            }

        }

        #region IDisposable
        private bool disposed;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                }
                disposed = true;
            }
        }
        ~WSCollectionHelper()
        {
            Dispose(false);
        }
        #endregion
    }
}

xml实体WSCollectionModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PTool.WebService
{
   public class WSCollectionModel
    {
        private string _function_name = string.Empty;
        private string _name_space = string.Empty;
        private string _class_name = string.Empty;
        private string _ws_url = string.Empty;

        public string Ws_url
        {
            get
            {
                return _ws_url;
            }

            set
            {
                _ws_url = value;
            }
        }

        public string Function_name
        {
            get
            {
                return _function_name;
            }

            set
            {
                _function_name = value;
            }
        }

        public string Name_space
        {
            get
            {
                return _name_space;
            }

            set
            {
                _name_space = value;
            }
        }

        public string Class_name
        {
            get
            {
                return _class_name;
            }

            set
            {
                _class_name = value;
            }
        }
    }
}

WSConfig.xml

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <wsmodel FunctionName="WorkRisk" ClassName="HookPlanService" NameSpace="http://tempuri.org/" WsUrl="http://192.168.2.247:8054/HookPlanService.asmx?wsdl"></wsmodel>
  <wsmodel FunctionName="WhatchSee" ClassName="HookPlanService" NameSpace="http://tempuri.org/" WsUrl="http://192.168.2.247:8054/HookPlanService.asmx?wsdl"></wsmodel>
  <wsmodel FunctionName="UserInfoAccess" ClassName="wsMonitor" NameSpace="http://tempuri.org/" WsUrl="http://10.169.153.40:8082/Access/wsMonitor.asmx?wsdl"></wsmodel>
</root>

 调用方式

 public static OtherRiskWs<WorkSee> GetWorkSeeInfo(string Date, string sta_name = "")
        {
            object[] obj = new object[2];
            obj[0] = Date;
            obj[1] = sta_name;
            object o = WSCollectionHelper.CurrentInstance.GetData("WhatchSee", obj);
            if (o == null)
            {
                return null;
            }
            string strjson = o.ToString();
            OtherRiskWs<WorkSee> info = PTool.Ajax.JsonSerializer.Deserializer(strjson, typeof(OtherRiskWs<WorkSee>)) as OtherRiskWs<WorkSee>;
            if (info == null)
            {
                return null;
            }
            if (info.data == null)
            {
                return null;
            }
            return info;
        }
萌橙 你瞅啥?
原文地址:https://www.cnblogs.com/daimaxuejia/p/11242115.html