WCF宿主与服务托管

简介:

若要公开WCF服务,需要提供一个运行服务的宿主环境。就像.NET CLR需要创建宿主环境以托管代码一般,WCF的宿主环境同样运行在进程的应用程序域中。在应用程序域中可以创建一个或多个ServiceHost实例,其关系如图一所示:


图一  托管ServiceHost

WCF并不推荐在应用程序域中创建多个ServiceHost实例。如果要托管多个服务,完全可以在一个宿主中通过多个Endpoint公开多个WCF服务。由于应用程序域对安全进行了隔离,如果需要提供不同的安全上下文,则有必要创建多个ServiceHost实例。

WCF的典型宿主包括以下四种:
1、"Self-Hosting" in a Managed Application(自托管宿主)
2、Managed Windows Services(Windows Services宿主)
3、Internet Information Services(IIS宿主)
4、Windows Process Activation Service(WAS宿主)

以下将通过一个具体的实例分别介绍这几种宿主的托管方式及其相关的注意事项。在这样的一个实例中,我们定义了如下的服务契约:

namespace BruceZhang.WCF.DocumentsExplorerServiceContract
{
    [ServiceContract]
     public  interface IDocumentsExplorerService
     {
        [OperationContract]
        [FaultContract(typeof(DirectoryNotFoundException))]
        DocumentList FetchDocuments( string homeDir);
        
        [OperationContract]
        Stream TransferDocument(Document document);        
     }    
}

服务的实现则如下所示:

namespace BruceZhang.WCF.DocumentsExplorerServiceImplementation
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
     public  class  DocumentsExplorerService : IDocumentsExplorerService
     {
         #region IDocumentsExplorerService Members

         public DocumentList FetchDocuments( string homeDir)
         {
             //implementation code
         }        

         public Stream TransferDocument(Document document)
         {
             //implementation code
         }

         #endregion     
     }
}

在服务契约的操作中,DocumentList与Document为自定义的数据契约:

namespace BruceZhang.WCF.DocumentsExplorerDataContract
{   
    [DataContract]
     public  class  Document
     {
         //DataMembers
     }
}
namespace BruceZhang.WCF.DocumentsExplorerDataContract
{
    [KnownType(typeof(Document))]    
    [CollectionDataContract]
     public  class  DocumentList:IList<Document>
     {
         //IList<Document> Methods
     }
}

注意以上定义的服务契约、服务类与数据契约的命名空间。

1、自托管宿主

利 用WCF提供的ServiceHost<T>提供的Open()和Close()方法,可以便于开发者在控制台应用程序,Windows应用 程序乃至于ASP.NET应用程序中托管服务。不管自宿主的环境是何种应用程序,实质上托管服务的方式都是一致的。例如在控制台应用程序中:

using (ServiceHost host =  new ServiceHost( typeof(DocumentsExplorerService)))
{
    host.Open();

    Console.WriteLine( "The Service had been launched.");
    Console.Read();
}

由 于ServiceHost实例是被创建在应用程序域中,因此我们必须保证宿主进程在调用服务期间不会被关闭,因此我们利用Console.Read()来 阻塞进程,以使得控制台应用程序能够一直运行,直到认为地关闭应用程序。如果是Windows应用程序,则可以将创建ServiceHost实例的代码放 在主窗体的相关代码中,保证服务宿主不会被关闭。

相应地,我们需要配置应用程序的app.config配置文件:

<configuration>
  <system.serviceModel>
    <services>
      <service name= "BruceZhang.WCF.DocumentsExplorerServiceImplementation.DocumentsExplorerService"behaviorConfiguration= "DocumentExplorerServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress= "http://localhost:8008/DocumentExplorerService"/>
          </baseAddresses>
        </host>          
        <endpoint
          address= ""
          binding= "basicHttpBinding"
          bindingConfiguration= "DocumentExplorerServiceBinding"
          contract= "BruceZhang.WCF.DocumentsExplorerServiceContract.IDocumentsExplorerService"/>
        <endpoint address= "mex" binding= "mexHttpBinding" contract= "IMetadataExchange"/>       
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name= "DocumentExplorerServiceBinding" sendTimeout= "00:10:00" transferMode= "Streamed"
                  messageEncoding= "Text" textEncoding= "utf-8" maxReceivedMessageSize= "9223372036854775807">          
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name= "DocumentExplorerServiceBehavior">
          <serviceMetadata httpGetEnabled= "true"/>          
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

注意,配置文件中的服务名必须包含服务契约以及服务类的命名空间。此外,在配置文件中我通过<baseAddresses>标签为服务添加了基地址,因此在endpoint中,address为""。

此时,调用服务的客户端配置文件也应与服务的配置保持一致:

<configuration>
  <system.serviceModel>
    <client>
      <endpoint        
        address= "http://localhost:8008/DocumentExplorerService"
        binding= "basicHttpBinding"
        bindingConfiguration= "DocumentExplorerServiceBinding"
        contract= "IDocumentsExplorerService"/>
      </client>
    <bindings>
      <basicHttpBinding>
        <binding name= "DocumentExplorerServiceBinding" sendTimeout= "00:10:00" transferMode= "Streamed"
                  messageEncoding= "Text" textEncoding= "utf-8" maxReceivedMessageSize= "9223372036854775807">
        </binding>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

注意,两个配置文件中的服务地址都是一样的,对于绑定的配置也基本一致。

在通常的企业应用中,我们很少会采用自宿主方式托管服务,这是因为这种方式必须要在应用程序运行下,客户端才能够调用服务,且并不便于随时启动和停止服务。 除了不具有易用性与易管理性之外,在可靠性、性能等诸多方面受到很多限制。但由于它简单、易于实现,因而往往用于开发期间的调试或演示环境。

自托管宿主支持所有的绑定。

2、Windows Services宿主

Windows Services宿主则完全克服了自托管宿主的缺点,它便于管理者方便地启动或停止服务,且在服务出现故障之后,能够重新启动服务。我们还可以通过 Service Control Manager(服务控制管理器),将服务设置为自动启动方式,省去了服务的管理工作。此外,Windows Services自身还提供了一定的安全性以及检测机制和日志机制。

Windows Services宿主的实现也非常简单。我们可以在Visual Studio中创建Windows Services项目。在创建项目之后,就可以创建一个继承了System.ServiceProcess.ServiceBase类的Windows服 务类。Windows服务类继承了ServiceBase类的OnStart()和OnStop()方法,完成Windows服务的启动与停止。我们可以 重写这两个方法,将ServiceHost的启动与关闭对应地放入这两个方法的实现中。例如我们创建的 DocumentsExplorerWindowsService类:

namespace BruceZhang.WCF.DocumentsExplorer
{
     public  partial  class  DocumentsExplorerWindowsService : ServiceBase
     {
         private ServiceHost m_serviceHost =  null;

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

         public DocumentsExplorerWindowsService()
         {
            InitializeComponent();

            ServiceName =  "DocumentsExplorerService";
         }

         protected  override  void OnStart( string[] args)
         {
             if (m_serviceHost !=  null)
             {
                m_serviceHost.Close();
             }

            m_serviceHost =  new ServiceHost( typeof(DocumentsExplorerService));
            m_serviceHost.Open();
         }

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

在 Main函数中,我们通过ServiceBase.Run()静态方法创建Windows服务实例,并在Windows服务类的构造函数中,调用 ServiceBase类的ServiceName属性指定服务名。在重写的OnStart()方法中,我们首先判断是否已经存在ServiceHost 实例,如果不存在,则创建它。创建ServiceHost实例的方法与自托管宿主方式相同。

为了完成ServiceHost实例的创建,我们同样需要在项目中添加app.config配置文件,配置文件的内容与前完全一样。

如 果在企业应用中要使用WCF技术,最佳的宿主方式我认为就是Windows Services,尤其是服务器的操作系统不是Vista的情况之下。它便于服务的管理,能够维持服务长时期的运行,同时它还支持所有的绑定,因而受到的 限制最小。然而,这种方式唯一的缺点却是对宿主的部署相对比较复杂,必须通过.NET提供的Installutil.exe工具完成对服务宿主的安装(也 可以通过安装包的自定义操作完成)。

若要完成对服务宿主的安装,我们还需要创建它的安装程序。我们可以自定义一个安装类,使其继承自 System.Configuration.Install.Installer类。更简单的办法则是通过Windows服务提供的设计时支持,直接创建 安装类。方法是在Windows服务例如DocumentsExplorerWindowsService的设计器视图下,通过单击右键,在快捷菜单中选 择“Add Installer”,如图二所示:


图二   添加安装程序

创建的安装程序ExplorerServiceInstaller如下所示:

namespace BruceZhang.WCF.DocumentsExplorer
{
     //It needs be ran at the command mode
     //Type installutil filename to install the windows service
     //Type services.msc to access the Service Control Manager(SCM) and browse the windows services
     //Type installutil /u filename to uninstall the windows service
    [RunInstaller(true)]
     public  partial  class  ExplorerServiceInstaller : Installer
     {
         private ServiceProcessInstaller m_process;
         private ServiceInstaller m_service;

         public ExplorerServiceInstaller()
         {
            InitializeComponent();

            m_process =  new ServiceProcessInstaller();
            m_process.Account = ServiceAccount.LocalSystem;
            m_service =  new ServiceInstaller();
            m_service.ServiceName =  "DocumentsExplorerService";
            Installers.Add(m_process);
            Installers.Add(m_service);
         }
     }
}

在 ExplorerServiceInstaller类中,ServiceAccount是一个枚举类型,可以设置为 LocalService,LocalSystem,NetworkService以及User值。其中,LocalService的安全性最 低,User值的安全性最高,需要有效的用户账号方才可以安装服务。

对于安装程序而言,也可以直接在设计器视图下设置它的属性。

安装程序直接建立在Windows服务的程序集中,编译之后会获得一个exe文件,例如DocumentsExplorer.exe。然后,我们通过在Visual Studio的Command Prompt模式下运行如下命令:
installutil DocumentsExplorer.exe
即可完成对服务宿主的安装。

打开服务控制管理器(可以在Command Prompt模式下输入Services.msc打开),可以看到名为DocumentsExplorerService的服务:


图三  服务控制管理器

如果要卸载该服务宿主,可以通过installutil的/u开关卸载。

在企业应用中,我们往往会将该Windows服务设置为自动启动,可以简化管理员的工作。

3、IIS宿主(说明,实例为IIS 6.0)

若要使用IIS宿主,需要为程序集中添加一个svc文件。我们可以通过为项目添加一个新项的方式添加svc文件:


图四   添加svc文件

我们也可以直接创建一个WCF Service应用程序作为IIS宿主,它会自动创建一个svc文件,如图五所示:


图五   创建WCF Service应用程序

创建的svc文件如图:


图六  创建的svc文件

WCF Service应用程序创建的svc文件以及通过添加新项获得svc文件,自动会创建WCF服务。因此,如果我们希望在svc文件中嵌入WCF服务的代码,则可以采取这种方式。例如:

<% @ ServiceHost Language= "C#" Debug= "true" Service= "BruceZhang.WCF.DocumentsExplorerServiceImplementation.DocumentsExplorerService"%>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;

using BruceZhang.WCF.DocumentsExplorerDataContract;

namespace BruceZhang.WCF.DocumentsExplorerServiceImplementation
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
     public  class  DocumentsExplorerService : IDocumentsExplorerService
     {
         //Service Implementation
     }
}

上述代码中的@ServiceHost指示符只能是在右键单击svc文件后,在View Marckup中才能够看到。

Svc文件通过@ServiceHost指示符指定它所要托管的服务,此外还指定了实现服务的语言、调用模式,还可以设置CodeBehind,指定服务代码。不过,在IIS托管中,服务代码或程序集文件受到一定的限制,它只能放在如下的其中一个位置中:
(1)    svc文件的内嵌代码中;
(2)    放在注册于GAC的单独程序集中;
(3)    驻留于应用程序的Bin文件夹内的程序集中(此时,bin文件夹不必include)
(4)    驻留于应用程序的App_Code文件夹的源代码文件中(根据Language的设置,或者为C#或者为VB);

即使我们将服务代码放在应用程序根目录下,或者其它文件夹中,然后通过CodeBehind指定代码的路径,仍然不能托管服务。

如 果服务契约与服务类是通过引用的方式在宿主应用程序中,则我们可以直接创建一个扩展名为.svc的单个文件,然后include到应用程序根目录下,如图六中的HostService.svc,该文件没有关联的cs文件。此时,在Visual Studio中直接打开该文件,并不能编写服务代码,而是指定@ServiceHost即可。

注意,上述方式的IIS宿主只能创建ServiceHost实例,如果是自定义的ServiceHost,则需要通过@ServiceHost的Factory来指定创建自定义ServiceHost的工厂类。例如这样的自定义ServiceHost以及相应的工厂类:

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace BruceZhang.WCF.DocumentsExplorerIISHost
{
     public  class  CustomServiceHostFactory : ServiceHostFactory
     {
         protected  override ServiceHost CreateServiceHost(
           Type serviceType, Uri[] baseAddresses)
         {
            CustomServiceHost customServiceHost =
                new CustomServiceHost(serviceType, baseAddresses);
             return customServiceHost;
         }
     }

     public  class  CustomServiceHost : ServiceHost
     {
         public CustomServiceHost(Type serviceType,  params Uri[]  baseAddresses)
            :  base(serviceType, baseAddresses)
         {
         }

         protected  override  void ApplyConfiguration()
         {
             base.ApplyConfiguration();
         }
     }
}

则@ServiceHost修改为:

<% @ ServiceHost Language= "C#" Debug= "true" Service= "BruceZhang.WCF.DocumentsExplorerServiceImplementation.DocumentsExplorerService" Factory= "BruceZhang.WCF.DocumentsExplorerIISHost.CustomServiceHostFactory"%>

在IIS托管应用程序中,我们需要创建web.config(注意,不是app.config),在<system.serviceModel>节中配置服务的相关内容:

<system.serviceModel>
    <services>
      <service behaviorConfiguration= "DocumentExplorerServiceBehavior"
       name= "BruceZhang.WCF.DocumentsExplorerServiceImplementation.DocumentsExplorerService">
        <endpoint address= "" binding= "basicHttpBinding" bindingConfiguration= "DocumentExplorerServiceBinding"
         contract= "BruceZhang.WCF.DocumentsExplorerServiceContract.IDocumentsExplorerService" />
        <endpoint address= "mex" binding= "mexHttpBinding" contract= "IMetadataExchange" />
      </service>      
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name= "DocumentExplorerServiceBinding" sendTimeout= "00:10:00" transferMode= "Streamed" messageEncoding= "Text" textEncoding= "utf-8" maxReceivedMessageSize= "9223372036854775807">
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name= "DocumentExplorerServiceBehavior">
          <serviceMetadata httpGetEnabled= "true" />
        </behavior>        
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

注 意,这里的配置文件与之前的宿主配置文件有个别的差异,就是没有指定服务的基地址。这是因为IIS托管会自动将svc文件的地址作为服务的基地址,我们无 法在配置文件中自行指定。Svc文件的地址为svc文件在IIS虚拟目录或站点所设置的路径。例如,我们在IIS中创建一个虚拟目录 DocumentsExplorer指向IIS宿主应用程序DocumentsExplorerIISHost,如图七所示:


图七  在IIS站点中为IIS创建虚拟目录

如果站点的属性没有做任何修改,使用默认的端口号,以及Localhost,则访问服务的基地址为http://localhost /DocumentsExplorer/HostService.svc。如果在配置文件的服务endpoint中设置地址为 DocumentsService,如:

<endpoint
address= "DocumentsService"
binding= "basicHttpBinding"
bindingConfiguration= "DocumentExplorerServiceBinding"
    contract= "BruceZhang.WCF.DocumentsExplorerServiceContract.IDocumentsExplorerService" />

则公开服务的地址则为http://localhost/DocumentsExplorer/HostService.svc/DocumentsServic。

通过IIS启动站点后,不需要做任何操作,服务宿主自动会创建ServiceHost实例或者Factory指定的自定义ServiceHost实例。

由于服务地址发生了变化,因此客户端的配置文件也需要做出相应的修改,必须将服务的地址设置为与之对应的地址。其中,服务的基地址为svc文件在IIS中的地址。

IIS 宿主是一种主要的服务托管方式,这是因为它具有易用性、可维护性、安全性、易于部署等多个优势。然而,它却具有一个致命的阿客流斯之踵,那就是它只支持 HTTP协议的传输绑定。特别对于局域网场景下,如果使用IIS宿主,就无法利用TCP传输的高效率,甚至无法使用MSMQ以及Peer to Peer传输。

IIS 7.0(基于Windows Vista和Windows Server 2007)提供的Windows激活服务(WAS)突破了IIS 6.0对于HTTP的依赖。

4、WAS宿主

WAS是IIS 7.0的一部分,但也可以独立地安装与配置。WAS支持所有可用的WCF传输协议、端口与队列。

利用WAS托管服务与IIS宿主托管服务的方法并没有太大的区别,仍然需要创建svc文件,同时在IIS中需要在站点中创建应有程序指向托管应用程序,还可以设置访问服务的别名与应用程序池。

由于WAS诉诸支持所有的绑定,因此此时的服务绑定并不会受到宿主的限制。

本文已在IT168发表:http://tech.it168.com/msoft/2007-12-11/200712111008739.shtml













本文转自wayfarer51CTO博客,原文链接:http://blog.51cto.com/wayfarer/280104,如需转载请自行联系原作者

相关文章
|
9月前
|
前端开发
WCF更新服务引用报错的原因之一
WCF更新服务引用报错的原因之一
|
8月前
|
C# 数据安全/隐私保护
c#如何创建WCF服务到发布(SqlServer版已经验证)
c#如何创建WCF服务到发布(SqlServer版已经验证)
38 0
|
8月前
|
安全 数据库连接 数据库
WCF服务创建到发布(SqlServer版)
在本示例开始之前,让我们先来了解一下什么是wcf? wcf有哪些特点? wcf是一个面向服务编程的综合分层架构。该架构的项层为服务模型层。 使用户用最少的时间和精力建立自己的软件产品和外界通信的模型。它使得开发者能够建立一个跨平台的安全、可信赖、事务性的解决方案。且能与已有系统兼容写作。 简单概括就是:一组数据通信的应用程序开发接口。
57 0
Visual Studio 2022 创建 WCF服务 找不到
Visual Studio 2022 创建 WCF服务 找不到
|
C++
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
102 0
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
WCF使用纯代码的方式进行服务寄宿
服务寄宿的目的是为了开启一个进程,为WCF服务提供一个运行的环境。通过为服务添加一个或者多个终结点,使之暴露给潜在的服务消费,服务消费者通过匹配的终结点对该服务进行调用,除去上面的两种寄宿方式,还可以以纯代码的方式实现服务的寄宿工作。
850 0
|
Windows
WCF服务寄宿到IIS
一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台。整合了原有的windows通讯的 .net Remoting,WebService,Socket的机制,并融合有HTTP和FTP的相关技术。
1046 0
WCF服务自我寄宿
WCF服务的寄宿方式 WCF寄宿方式是一种非常灵活的操作,可以寄宿在各种进程之中,常见的寄宿有: IIS服务、Windows服务、Winform程序、控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便、高效提供服务调用。
994 0
|
网络架构
(纯代码)快速创建wcf rest 服务
因为有一个小工具需要和其它的业务对接数据,所以就试一下看能不能弄一个无需配置快速对接的方法出来,百(以)度(讹)过(传)后(讹),最后还是对照wcf配置对象调试出来了: 1.创建WebHttpBinding 2.
979 0