WCF學習之旅—WCF服務的Windows 服務程式寄宿(十一)

来源:http://www.cnblogs.com/chillsrc/archive/2016/05/24/5523490.html
-Advertisement-
Play Games

上接 WCF學習之旅—WCF服務部署到IIS7.5(九) WCF學習之旅—WCF服務部署到應用程式(十) 七 WCF服務的Windows 服務程式寄宿 這種方式的服務寄宿,和IIS一樣有一個一樣的優點,系統啟動後,WCF服務也會跟著啟動了,不用人工干預,也是一種較好的寄宿方式。 (1) 在解決方案下 ...


上接    WCF學習之旅—WCF服務部署到IIS7.5(九)

          WCF學習之旅—WCF服務部署到應用程式(十)

 

七 WCF服務的Windows 服務程式寄宿

       這種方式的服務寄宿,和IIS一樣有一個一樣的優點,系統啟動後,WCF服務也會跟著啟動了,不用人工干預,也是一種較好的寄宿方式。

      (1) 在解決方案下新建控制台輸出項目 WinServiceHosting。如下圖。

    

    (2)添加 System.ServiceModel.dll 的引用。

    (3)添加 WCF 服務類庫(WcfServiceLib)的項目引用。

    (4) 添加響應的Window服務類。如下圖。

    

    (5)然後在服務類啟動裡面添加WCF的寄宿代碼,如下所示。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; 

namespace WinSvrviceHosting
{
    partial class WCFServiceMgr : ServiceBase
    {
        string Name = "WCF服務Windows Service寄宿";
        public WCFServiceMgr()
        {

            InitializeComponent();
            this.ServiceName = Name;
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此處添加代碼以啟動服務。

            try
            {
                svrHost = new ServiceHost(typeof(WCFServiceMgr));
                if (svrHost.State != CommunicationState.Opened)
                {
                    svrHost.Open();
                }
            }

            catch (Exception ex)
            {
                Logger.Log(ex,string.Empty,string.Empty,string.Empty);

            }

            Logger.Log(Name + DateTime.Now.ToShortTimeString() + "已成功調用了服務一次。");
            Logger.Log(Name + "已成功啟動。");
        }

        protected override void OnStop()
        {
            // TODO: 在此處添加代碼以執行停止服務所需的關閉操作。
            if (svrHost!=null)
            {
                svrHost.Close();
                svrHost = null;

            }
        }

        private static object syncRoot = new Object();//同步鎖
        private ServiceHost svrHost = null; //寄宿服務對象 

    } 

}

 

         (6) 在WCFServiceMgr.cs的設計界面上右鍵,在彈出菜單中選擇“添加安裝程式”。如下圖1。這時,項目里會自動生成一個ProjectInstaller.cs文件。如下圖2。

 

 圖1

 

圖2

 

        ( 7) 選中serviceInstaller1,打開它的屬性視圖,修改屬性。如下圖所示:

 

       (8) 接著選中serviceProcessInstaller1,打開它的屬性視圖,修改屬性。如下圖:(這裡服務賬號也可以是其他的。)

 

 

       (9) 為了實現通過該控制台程式實現參數化安裝和卸載服務,我們需要攔截控制台的參數,併進行相應的操作,如下所示。

using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; 

namespace WinSvrviceHosting

{

    class Program

    {
        static void Main(string[] args)
        {

            ServiceController service = new ServiceController(WCFServiceMgr.Name);           

            // 運行服務

            if (args.Length == 0)
            {

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] { new WCFServiceMgr() };
                ServiceBase.Run(ServicesToRun);
            }

            else if (args[0].ToLower() == "/i" || args[0].ToLower() == "-i")
            {

                #region 安裝服務

                if (!IsServiceExisted("WCFServiceMgr"))
                {
                    try

                    {

                        string[] cmdline = { };

                        string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
                        TransactedInstaller transactedInstaller = new TransactedInstaller();
                        AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline);
                        transactedInstaller.Installers.Add(assemblyInstaller);

                        transactedInstaller.Install(new System.Collections.Hashtable());
                        TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10);
                        service.Start();                        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                    }

                    catch (Exception ex)
                    {                        Logger.Log(ex,string.Empty,string.Empty,string.Empty);
                        throw ex;

                    }
                }

                #endregion

            }
            else if (args[0].ToLower() == "/u" || args[0].ToLower() == "-u")

            {

                #region 刪除服務

                try
                {

                    if (IsServiceExisted("WCFServiceMgr"))
                    {

                        string[] cmdline = { };
                        string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; 

                        TransactedInstaller transactedInstaller = new TransactedInstaller();
                        AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline);
                        transactedInstaller.Installers.Add(assemblyInstaller);
                        transactedInstaller.Uninstall(null);
                    }
                }

                catch (Exception ex)
                {
                    Logger.Log(ex, string.Empty, string.Empty, string.Empty);
                    throw ex;
                }
                #endregion
            } 

        }

        #region 檢查服務存在的存在性 

        /// <summary> 
        /// 檢查服務存在的存在性 
        /// </summary> 
        /// <param name=" NameService ">服務名</param> 
        /// <returns>存在返回 true,否則返回 false;</returns> 
        public static bool IsServiceExisted(string NameService)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName.ToLower() == NameService.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

    }

}

 

 

       (10)添加應用程式配置文件App.config,這次我們使用配置的方式進行WCF服務的公佈,WCF服務配置代碼如下。

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <startup>

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />

    </startup> 

  <system.serviceModel>   

    <diagnostics>

      <messageLogging logEntireMessage="true" logKnownPii="false" logMalformedMessages="true"
        logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
      <endToEndTracing propagateActivity="true" activityTracing="true"

        messageFlowTracing="true" />
    </diagnostics>

    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8080/BookService/metadata" />
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>

      </serviceBehaviors>
    

    </behaviors>

    <services>

      <service behaviorConfiguration="metadataBehavior" name="WcfServiceLib.BookService">

        <endpoint address="http://127.0.0.1:8080/BookService" binding="wsHttpBinding"

        contract="WcfServiceLib.IBookService" />

      </service>

    </services>

  </system.serviceModel>

</configuration>

 

        (11) 編譯程式成功後,我們添加兩個批處理的DOS腳本來實現執行程式的自動安裝和卸載,如下所示。

--安裝腳本

"WinSvrviceHosting.exe" -i

pause

 

--卸載腳本

"WinSvrviceHosting.exe" -u

Pause

(12) 我們首先執行安裝腳本。結果如下圖。

 

        (13) 順利執行腳本後,“管理工具—》服務”,在服務列表裡面就增加一個服務項目了。如下圖。

 

        (14) 執行卸載腳本,腳本就會卸載服務。如下圖。

 

 

   建立客戶端

      使用我們在Console寄宿程式編寫的客戶端,去訪問Windows窗體宿主程式的WCF服務。

 

 

 


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

-Advertisement-
Play Games
更多相關文章
  • Insus.NET開發這樣多網站,客戶一直沒有這個要求。不過,現在有客戶有這樣的要求了。線上用戶訪問人數,也就是說,要為網站寫一個計數器,計數器的初始值為0,網站一開始運行時(Application_Start),就開始統計,當有用戶訪問時(Session_Start)計數器加1,當用戶訪問離開時( ...
  • 三大範式一直沒有記住,看了這個有了理解!挺好的記著,以後忘了,可以再看看! 為了建立冗餘較小、結構合理的資料庫,設計資料庫時必須遵循一定的規則。在關係型資料庫中這種規則就稱為範式。範式是符合某一種設計要求的總結。要想設計一個結構合理的關係型資料庫,必須滿足一定的範式。 在實際開發中最為常見的設計範式 ...
  • 環境:Vs2103(TFS2013) 目的:去掉別人項目里的TFS控制,因為每次打開時會有提示信息 解決方法: 1.刪除隱藏的.$tf文件夾,搜索*.vssscc和*.vspscc這兩個尾碼的文件,刪除找到的文件. 2.使用文本編輯器打開*.sln文件,找到 GlobalSection(TeamFo ...
  • 剛到新單位,學習他們的源代碼,代碼里讀寫系統配置文件的XML代碼比較老套,直接寫在一個系統配置類里,沒有進行類的拆分,造成類很龐大,同時,操作XML的讀寫操作都是使用SetAttribute和node.Attribute(name)方法,因此,想到結合之前所做的XML操作,完成了一個能夠讀取XML文 ...
  • 寫入: 插入100萬條數據:用InsertMany,耗時16s左右。 讀取: 讀取300萬條數據,耗時3600毫秒。 ...
  • ...
  • 這次要分享的是C#Task任務的幾個列子,感覺最實用的是封裝的分頁任務執行方法,這個方法步奏也是目前在我工作中執行多任務常用的,不知道各位也有這用的情況,那麼開始吧。 1.順序任務執行 1 //順序任務執行 2 Task.Factory.StartNew<int>(() => { Console.W ...
  • 關於面試中涉及到的事件的問題,我們只需要抓住幾個關鍵點就好了: 定義事件: 5 } ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...