WCF服務寄宿IIS與Windows服務

 
WCF是Windows平臺下程序間通信的應用程序框架。整合和 .net Remoting,WebService,Socket的機制,是用來開發windows平臺上分佈式開發的最佳選擇。wcf程序的運行須要一個宿主ServiceHost,咱們能夠選用控制檯應用程序,也能夠選擇IIS寄宿,還能夠選擇windows 服務寄宿。相較與控制檯程序,IIS,和Windows服務比較穩定。並且你們不會時不時的去重啓下IIS下的網站,或者windows服務。

在IIS下寄宿Wcf

咱們新建一個類庫項目html

在項目下添加一個ICalculator接口類,實現wcf 服務契約,操做契約接口web

using System.ServiceModel;
namespace IISServices
{
    [ServiceContract(Name = "CalculatorService")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double x, double y);

        [OperationContract]
        double Subtract(double x, double y);

        [OperationContract]
        double Multiply(double x, double y);

        [OperationContract]
        double Divide(double x, double y);
    }
}

新建一個服務類CalculatorService,實現服務契約接口ICalculatorwindows

namespace IISServices
{
    public class CalculatorService : ICalculator
    {
        public double Add(double x, double y)
        {
            return x + y;
        }

        public double Subtract(double x, double y)
        {
            return x - y;
        }

        public double Multiply(double x, double y)
        {
            return x * y;
        }

        public double Divide(double x, double y)
        {
            return x / y;
        }
    }
}

添加一個文件,文件名爲CalculatorService.svc就是咱們用來尋找服務對外暴漏的入口。只須要添加一行代碼就能夠。當咱們訪問服務的時候IIS會尋找咱們這個svc文件來找到咱們提供的服務。框架

 <%@ServiceHost Service="IISServices.CalculatorService"%>

添加一個web.Config文件,添加system.serviceModel節點的配置信息。裏面不須要配置咱們訪問服務的地址,由於IIS下咱們網站的地址就是咱們訪問服務的地址。分佈式

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="metadataBehavior" name="IISServices.CalculatorService">
        <endpoint  binding="wsHttpBinding" contract="IISServices.ICalculator" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

項目詳細以下,另外應用裏面須要添加System.ServiceModel這個dll引用,wcf的大部分實現都在這個類庫裏面:ide

咱們在IIS下面新建一個網站,根目錄只須要添加web.Config,svc服務文件便可,bin下面放咱們生成的IISServices.dll以下:函數

網站訪問端口咱們配置爲82,啓動網站。網站

在咱們須要引用服務的類庫或exe上添加服務引用http://localhost:82/CalculatorService.svc,就能夠找到咱們須要的服務了。ui

在Windows服務下寄宿wcf服務

咱們新建一個控制檯應用程序Service。添加下面這三個類庫引用this

  • System.ServiceModel.dll

  • System.ServiceProcess.dll

  • System.Configuration.Install.dll

將Programs.cs修改成Service.cs,添加代碼以下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration;
using System.Configuration.Install;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }

    // Implement the ICalculator service contract in a service class.
    public class CalculatorService : ICalculator
    {
        // Implement the ICalculator methods.
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            return result;
        }

        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            return result;
        }

        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            return result;
        }

        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            return result;
        }
    }

    public class CalculatorWindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;
        public CalculatorWindowsService()
        {
            // Name the Windows Service
            ServiceName = "WCFWindowsServiceSample";
        }

        public static void Main()
        {
            ServiceBase.Run(new CalculatorWindowsService());
        }

        // Start the Windows service.
        protected override void OnStart(string[] args)
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            // Create a ServiceHost for the CalculatorService type and 
            // provide the base address.
            serviceHost = new ServiceHost(typeof(CalculatorService));

            // Open the ServiceHostBase to create listeners and start 
            // listening for messages.
            serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }

    // Provide the ProjectInstaller class which allows 
    // the service to be installed by the Installutil.exe tool
    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = "WCFWindowsServiceSample";
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}
View Code

在App.Config裏面添加配置節點ServiceModel以下:

 <system.serviceModel>
    <services>
      <!-- This section is optional with the new configuration model
           introduced in .NET Framework 4. -->
      <service name="Microsoft.ServiceModel.Samples.CalculatorService"
               behaviorConfiguration="CalculatorServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
          </baseAddresses>
        </host>
        <!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModelSamples/service  -->
        <endpoint address=""
                  binding="wsHttpBinding"
                  contract="Microsoft.ServiceModel.Samples.ICalculator" />
        <!-- the mex endpoint is exposed at http://localhost:8000/ServiceModelSamples/service/mex -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="CalculatorServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
View Code

生成文件,注意看程序的入口main函數ServiceBase.Run(new CalculatorWindowsService());在main函數裏面程序調用了windows服務。咱們這個項目本質上是一個windows服務。windows服務不能夠直接運行,須要先安裝。咱們使用管理員身份打開cmd.exe

進入咱們的.net安裝目錄,我這個是安裝的4.0,因此進入C:\Windows\Microsoft.NET\Framework64\v4.0.30319文件夾,找到該文件夾下面的InstallUtil.exe程序。在cmd裏面輸入以下,回車

進入.net安裝文件夾,輸入InstallUtil.exe "生成服務所在的路徑",注意這兒最好給路徑加上引號,沒有引號若是碰到空格可能報錯。

安裝後若是出現下面的successfully,說明服務安裝完成。

而後咱們到windows服務裏面啓動該服務。

啓動服務後,在須要引用該服務的類庫或者exe程序上添加服務引用,路徑爲咱們App.config裏面的 <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>基地址

點擊轉到,出現CalculatorService說明咱們配置成功。

 

注:

安裝 Windows 服務: installutil bin\service.exe 

卸載Windows服務: installutil /u bin\service.exe 或者 sc delete 服務名

啓動Windows服務: net start WCFWindowsServiceSample

中止Windows服務: type net stop WCFWindowsServiceSample

windows服務的寄宿,參考msdn:https://msdn.microsoft.com/zh-cn/library/ms733069.aspx

本文地址:http://www.cnblogs.com/santian/p/4397235.html

博客地址:一天兩天三天

轉載請以超連接形式標明文章原始出處。
相關文章
相關標籤/搜索