WCF學習之旅—WCF服務的批量寄宿(十三)


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

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

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

         WCF學習之旅—WCF服務的WAS寄宿(十二)

 

九、 無svc文件服務激活的原理:

  在WCF4.0里,通過提供一種虛擬的服務類型映射機制來實現WCF服務的激活。我們可以在配置文件里指定服務類型和相對地址之間的映射關系。這就使得我們可以在不是要.svc文件的情況下,在WAS/IIS里托管WCF服務程序。

1)     關於服務激活,這里一個重要的配置元素就是serviceActivation。我們可以定義服務類型和相對地址之間的映射關系。在配置文件里serviceActivations節點屬於serviceHostingEnvironment>。一個簡單的服務類型和相對地址之間的映射如下:
   

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="false" />
    </system.webServer>
        <system.serviceModel>
           <serviceHostingEnvironment>   

            <serviceActivations>     
          <add relativeAddress="BookService.svc" service="WcfServiceLib.BookService"/>       
            </serviceActivations>  
            </serviceHostingEnvironment>  

   </system.serviceModel>  
    <system.web>
        <compilation defaultLanguage="c#" />
    </system.web>
</configuration>

 

  使用這個配置,我們就可以在WCF4.0里,使用http的方式,無svc文件激活BookService。注意<serviceHostingEnvironment>屬於一個應用程序級別的配置。我們必須把它放置在<system.serviceModel>
節點下。此外,serviceHostingEnvironment繼承自machinetoApplication。如果我們在machine注冊單個服務,程序里的每個服務必須繼承該服務。

  這種通過配置設置的激活映射,支持http和非http協議。我們需要在相對地址relatativeAddress 里擴展文件名,例如.svc、.xoml 或.xamlx。我們也可以定義自己的處理擴展組件,然后在這里配置,那么WCF也會做類似的映射。為了避免沖突,我們在配置文件里定義的<serviceActivations>會代替svc的內容。也就是配置文件的設置優先級會比較高。

 

2)    IIS部署:部署方式同本文WCF服務部署到IIS7.5。

  • 指定網站的ASP.NET的版本,這里注意版本為4.0,默認的版本是2.0。

     網站ASP.NET的版本配置如圖所示:

 

3)   這里直接啟動瀏覽器,可以在瀏覽器里查看到服務的信息。如果啟用服務元數據頁面,可以查看到服務的WSDL信息。頁面如下: 

 

十、批量寄宿

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

 

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

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

(4) 創建配置文件,在配置文件中添加兩個配置項

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.serviceModel>
    <bindings>
       <webHttpBinding>
         <binding name="RestWebBinding">
         </binding>
       </webHttpBinding>
     </bindings>
        <behaviors>
      <serviceBehaviors>
        <behavior name="metadataBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8888/BookService/metadata" />
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
          <behavior name="RestServiceBehavior">
         </behavior>
      </serviceBehaviors>
       <endpointBehaviors>
         <behavior name="RestWebBehavior">
           <!--這里必須設置-->

           <webHttp />
         </behavior>

       </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="metadataBehavior" name=" WcfServiceLib.BookService">
        <endpoint address="http://127.0.0.1:8888/BookService" binding="wsHttpBinding"

        contract=" WcfServiceLib.IBookService" />
      </service>
      <service name=" WcfServiceLib.BookRestService" behaviorConfiguration="RestServiceBehavior">
         <endpoint address="http://127.0.0.1:8888/" behaviorConfiguration="RestWebBehavior"

                   binding="webHttpBinding" bindingConfiguration="RestWebBinding" contract=" WcfServiceLib.IBookRestService">

         </endpoint>
       </service>
    </services>
  </system.serviceModel>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings> 

     <add name="Entities" connectionString="metadata=res://*/BookModel.csdl|res://*/BookModel.ssdl|res://*/BookModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;initial catalog=Test;integrated security=SSPI;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

  </connectionStrings>
</configuration>

 

  (5)創建宿主程序,代碼如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using WcfServiceLib;
 

namespace BatHosting
{
    class Program
    {
        /// <summary>
        /// 批量寄宿
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {

            try
            {
                Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);              

                ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");
                foreach (ServiceElement el in svcmod.Services.Services)
                {

                    Type svcType = Type.GetType(el.Name + "," + "SCF.WcfService");
                    if (svcType == null)
                        Console.WriteLine("WCF Service Type " + el.Name + " 在配置文件中的名稱.");
                    ServiceHost host = new ServiceHost(svcType);
                    host.Opened += delegate
                    {
                        Console.WriteLine(string.Format("{0},使用配置文件,批量寄宿!",svcType.ToString()));

                    };

                    host.Open();
                    Console.ForegroundColor = ConsoleColor.Yellow;

                    foreach (ServiceEndpoint se in host.Description.Endpoints)
                    {
                        Console.WriteLine("[終結點]: {0}\r\n\t[A-地址]: {1} \r\n\t [B-綁定]: {2} \r\n\t [C-協定]: {3}",
                     se.Name, se.Address, se.Binding.Name, se.Contract.Name);
                    }
                }
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }           
        }
    }
}

 

 (5)運行宿主程序,在運行客戶端進行調用之前,需要先運行宿主程序。如下圖所示,則說明宿主建立成功。

 

 

十一、總結

  通過上面的幾個例子,我們實現了控制台宿主、Form宿主、IIS寄宿、WAS宿主(基於TCP協議)、批量寄宿等的實現。在實際的開發過程中,我們大部份都使用IIS做宿主,方便、快捷;有時候我們還會用到基於Windows服務的宿主


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM