宿主多個WCF服務

来源:http://www.cnblogs.com/gfjin/archive/2017/12/21/8079399.html
-Advertisement-
Play Games

在工作中經常使用WinForm來承載多個WCF服務,由於底層代碼無權查看,故自己研究寫了一個類實現同樣的功能並加入對單個WCS服務的控制,能夠選擇其中的一個會多個服務進行啟動,停止的控制,並且支持雙工通訊模式,廢話不多說直接上代碼: namespace Gaofajin.Net{ public cl ...


在工作中經常使用WinForm來承載多個WCF服務,由於底層代碼無權查看,故自己研究寫了一個類實現同樣的功能並加入對單個WCS服務的控制,能夠選擇其中的一個會多個服務進行啟動,停止的控制,並且支持雙工通訊模式,廢話不多說直接上代碼:

namespace Gaofajin.Net
{

 public class WcfRunerNew
    {

        #region 變數定義
        public int Port { get; set; } = 8080;
        public bool IsRunning = false;
        List<WcfStruct> list = new List<WcfStruct>() ;
       // public bool UseDuplex { get; } = false;
        #endregion
        #region 構造函數
        public WcfRunerNew(int port)
        {
            Port = port;
        }
        public WcfRunerNew()
        {

        }
        System.ServiceModel.Channels.Binding InitBinding(bool duplex)
        {
            System.ServiceModel.Channels.Binding binding = null;
            if (!duplex)
                binding = new WSHttpBinding()
                {
                    SendTimeout = new TimeSpan(1, 0, 0, 0, 0),
                    ReceiveTimeout = new TimeSpan(1, 0, 0, 0, 0),
                    MaxReceivedMessageSize = 2147483647,

                };
            else binding = new WSDualHttpBinding()
            {
                SendTimeout = new TimeSpan(1, 0, 0, 0, 0),
                ReceiveTimeout = new TimeSpan(1, 0, 0, 0, 0),
                MaxReceivedMessageSize = 2147483647,

            };
            return binding;
        }
        #endregion
        #region 添加服務
        public string AddService(Type Interface, Type Class, string Name, string host, bool duplex)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                Name = Name,
                C = Class,
                I = Interface,
                Host = host,
                UseDuplex = duplex,

            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class, string Name, int Port, bool duplex)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                Name = Name,
                C = Class,
                I = Interface,
                Port = Port,
                UseDuplex = duplex,

            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class, string Name, bool duplex)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                Name = Name,
                C = Class,
                I = Interface,
                UseDuplex = duplex,
            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class, string Name, int port)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                Name = Name,
                C = Class,
                I = Interface,
                Port = port
            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class, string Name, string host)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                Name = Name,
                C = Class,
                I = Interface,
                Host = host
            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class, bool duplex)
        {
            WcfStruct wcf = new WcfStruct()
            {
                C = Class,
                I = Interface,
                UseDuplex = duplex,
            };
            list.Add(wcf);
            return "添加服務成功!";
        }
        public string AddService(Type Interface, Type Class, string Name)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                Name = Name,
                C = Class,
                I = Interface,
            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class, int Port)
        {
            string msg = "添加服務成功!";
            WcfStruct wcf = new WcfStruct()
            {
                C = Class,
                I = Interface,
                Port = Port,
            };
            foreach (var wcf1 in list)
            {
                if (wcf1.Name == wcf.Name && !string.IsNullOrEmpty(wcf.Name))
                {
                    return string.Format("添加WCF服務失敗,名為:{0}的服務已存在!多個WCF服務名字不允許重覆!", wcf.Name);
                }
            }
            list.Add(wcf);
            return msg;
        }
        public string AddService(Type Interface, Type Class)
        {
            WcfStruct wcf = new WcfStruct()
            {
                C = Class,
                I = Interface,
            };
            list.Add(wcf);

            return "添加服務成功!";
        }
        #endregion
        #region 獲取所有服務
        public List<WcfStruct> GetServiceList() =>list;
        #endregion
        #region 停止指定服務
        public string  StopServiceByName(string Name)
        {
            if (string.IsNullOrEmpty(Name))
            {
                return "停止指定服務必須提供服務名!";
            }
            foreach(var m in list)
            {
                if (m.Name == Name)
                {
                    if(m.sh!=null && m.sh.State != CommunicationState.Closed)
                    {
                        m.sh.Close();
                    }
                    if (m.wsh != null && m.wsh.State != CommunicationState.Closed)
                    {
                        m.wsh.Close();
                    }
                   
                    return "停止指定服務成功!服務名"+Name;
                }
            }
            return "停止制定的服務錯誤服務名:"+Name;

        }
        #endregion
        #region 啟動指定的服務
        public string StartServiceByName(string Name)
        {
            if (string.IsNullOrEmpty(Name))
            {
                return "啟動指定服務必須提供服務名!";
            }
            string err = string.Empty;
            try
            {
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    if (list[i].Name == Name)
                    {
                        if (list[i].sh.State != CommunicationState.Closed)
                        {
                            list[i].sh.Close();
                        }
                        string HostAddr = (!list[i].Host.Contains("http://")) ? "http://" + list[i].Host + "/" + Name : list[i].Host + "/" + Name;
                        ServiceHost sh = new ServiceHost(list[i].C, new Uri(HostAddr));
                        err += "服務地址:" + HostAddr + "\r\n";
                        sh.AddServiceEndpoint(list[i].I, InitBinding(list[i].UseDuplex), list[i].Name);
                        ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                        behavior.HttpGetEnabled = true;
                        //HostAddr += "/wsdl";
                        behavior.HttpGetUrl = new Uri(HostAddr);
                        err += "元數據地址:" + HostAddr.ToString() + "\r\n";
                        sh.Description.Behaviors.Add(behavior);
                        sh.Description.Name = Name;
                        sh.Open();
                        list[i].sh = sh;
                        //if (list[0].UseWeb)
                        //{
                        //    WebServiceHost webServiceHost = new WebServiceHost(list[i].C, new Uri(HostAddr));
                        //    webServiceHost.Open();
                        //    list[0].wsh = webServiceHost;
                        //}
                        return "啟動指定服務成功!服務名" + Name+"服務地址:"+HostAddr;
                    }
                }
                return "位置找到名為:" + Name + "的服務定義!";
            }
            catch(Exception ex)
            {
                return "啟動指定的服務錯誤:" + ex.Message;
            }
        }
        #endregion
        #region 啟動服務
        /// <summary>
        /// 啟動服務
        /// </summary>
        /// <param name="host">發佈地址</param>
        /// <param name="err">返回消息</param>
        public string Start()
        {
           string err = "啟動服務成功!\r\n";
            string ip = getHost();
            if (string.IsNullOrEmpty(ip))
            {
                err = "自動識別本機IP地址失敗!無法繼續創建服務!";
                return err;
            }
            try
            {
                foreach (WcfStruct ws in list)
                {
                    int potr=(ws.Port != 0 ? ws.Port : Port);
                    string host = (!string.IsNullOrEmpty(ws.Host)?ws.Host:ip+":"+potr);
                    string host1 =(!host.Contains("http://"))? "http://" + host: host;
                    string HostAddr = host1+"/"+(!string.IsNullOrEmpty(ws.Name)?ws.Name:ws.C.Name);
                    ServiceHost sh = new ServiceHost(ws.C, new Uri(HostAddr));
                    err += "服務地址:" + HostAddr + "\r\n";
                    sh.AddServiceEndpoint(ws.I, InitBinding(ws.UseDuplex),(!string.IsNullOrEmpty(ws.Name) ? ws.Name : ws.C.Name));
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri(HostAddr);
                    err += "元數據地址:" + HostAddr.ToString() + "\r\n";
                    sh.Description.Behaviors.RemoveAll<ServiceMetadataBehavior>();
                    sh.Description.Behaviors.Add(behavior);
                    sh.Description.Name = (!string.IsNullOrEmpty(ws.Name) ? ws.Name : ws.C.Name);
                    sh.Open();
                    ws.sh = sh;
                    ws.Host = host;
                    ws.Port = potr;
                    ws.Name = (!string.IsNullOrEmpty(ws.Name) ? ws.Name : ws.C.Name);
                    //if (ws.UseWeb)
                    //{
                    //    WebServiceHost webServiceHost = new WebServiceHost(ws.C, new Uri(HostAddr));
                    //    webServiceHost.Open();
                    //    ws.wsh = webServiceHost;
                    //    err += ws.wsh.Description.Endpoints[0].ListenUri.ToString();
                    //}
                   
                }
                IsRunning = true;
                return err;
            }catch(Exception ex)
            {
                Stop();
                IsRunning = false;
                err = "啟動服務異常:" + ex.Message;
                return err;
            }
        }
        #endregion
        #region 停止所有服務
        /// <summary>
        /// 停止Wcf服務
        /// </summary>
        /// <param name="err"></param>
        public string Stop()
        {
          string  err = "停止服務成功!";
            try
            {
                foreach (WcfStruct ws in list)
                {
                    if (ws.sh!=null&&ws.sh.State != CommunicationState.Closed)
                    {
                        ws.sh.Close();
                    }
                    if (ws.wsh != null&& ws.wsh.State != CommunicationState.Closed)
                    {
                        ws.wsh.Close();
                    }
                }
                list.Clear();
                IsRunning = false;
            }catch(Exception ex)
            {
                err = "停止服務發生異常:" + ex.Message;
            }
            return err;
        }
        #endregion
        #region 取host
        string getHost()
        {
            string hostname = Dns.GetHostName();
          IPHostEntry He=  Dns.GetHostEntry(hostname);
            foreach (var m in He.AddressList)
            {
                if (m.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                   return  m.ToString();
                   // return m.Address.ToString();
                }
            }
            return "";
        }
      
        #endregion
    }
 /// <summary>
 /// Wcf服務參數存儲結構類
 /// </summary>
    public class WcfStruct
    {
        internal ServiceHost sh { get; set; }
        internal WebServiceHost wsh { get; set; }
        internal string Name { get; set; }
        internal string Host { get; set; }
        internal int Port { get; set; }
        internal Type C { get; set; }
        internal Type I { get; set; }
        internal bool UseDuplex { get; set; } = false;
        internal bool UseWeb { get; set; } = false;
    }

}

簡單調用實例代碼:

Gaofajin.Net.WcfRunerNew wcfRuner = new Gaofajin.Net.WcfRunerNew();
            WriteLine(wcfRuner.AddService(typeof(IMessage), typeof(MessageSvr),"MessageSvr","http://localhost:9999",true));
            WriteLine(wcfRuner.AddService(typeof(IService1), typeof(Service1),false));
            WriteLine(wcfRuner.AddService(typeof(IService1), typeof(Service1)));
            WriteLine(wcfRuner.Start());


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一Socket介紹: 網路上的兩個程式通過一個雙向的通信連接實現數據的交換,這個連接的一端稱為一個socket。 建立網路通信連接至少要一對埠號(socket)。socket本質是編程介面(API),對TCP/IP的封裝,TCP/IP也要提供可供程式員做網路開發所用的介面,這就是Socket編程接 ...
  • using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading;... ...
  • 三層架構,我們一般說的三層架構通常指的是:1、表現層(UI):就是展現給用戶的界面,無論是網站前臺還是應用程式界面;2、業務邏輯層(BLL):針對具體問題的邏輯操作;3、數據訪問層(DAL):對數據進行操作。其他的層級基本都是在這三層之上的補充。 UI(User Interface)表示層: 就是我 ...
  • 本示例學習如何閱讀有多個await方法方法時,程式的實際流程是怎麼樣的,理解await的非同步調用 。 ...
  • I was reading a post about some common C# interview questions, and thought I’d share some of mine. These are questions that I asked in interviews, or ... ...
  • 在Excel中如果能夠將具有多級明細的數據進行分組顯示,可以清晰地展示數據表格的整體結構,使整個文檔具有一定層次感。根據需要設置顯示或者隱藏分類數據下的詳細信息,在便於數據查看、管理的同時也使文檔更具美觀性。那麼,在C#中如何來創建Excel數據的多級分組顯示呢?下麵將進行詳細闡述。方法中使用了免費 ...
  • Highcharts .NET allows developers to make charts using Highcharts API with the Microsoft .NET Framework (ASP.NET MVC 4+). ...
  • 個人資料庫幫助類:提供兩種訪問方式OleDb(需安裝Oracle客戶端)和 Oracle.ManagedDataAccess.Client(需Oracle.ManagedDataAccess.dll) 多說無益上代碼: #region Info/* ************************* ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...