【引】Hosting WCF Services in Windows Activation Service
2013-07-31 10:30 朱峰(Peter.zhu) 阅读(699) 评论(0) 编辑 收藏 举报Hosting WCF Services in Windows Activation Service
Windows Activation Service (WAS), introduced with Windows Vista, is the new process activation mechanism that ships with IIS 7.0. WAS builds on the existing IIS 6.0 process and hosting models, but is much more powerful because it provides support for other protocols besides HTTP, such as TCP and Named Pipes.
By hosting the Windows Communication Foundation (WCF) services in WAS, you can take advantage of WAS features such as process recycling, rapid failover protection, and the common configuration system, all of which were previously available only to HTTP-based applications. This article explores the steps involved in using WAS to host and consume WCF services.
Hosting Options for WCF
When hosting WCF services, you now have three choices:
- Windows Activation Service (WAS) hosting environment
- Executable (.exe) applications (including Console and Windows Forms applications)
- Windows Services
The WAS hosting environment is a broad concept that extends the ASP.NET HTTP pipeline hosting concept primarily used for ASMX web services. WAS is implemented as a Windows service in Windows Vista. As a standalone Windows component it's completely separate from the legacy IIS host and does not carry all the overhead associated with IIS while still providing a flexible and stable hosting environment for WCF services. In addition, by providing a protocol-agnostic activation mechanism (meaning you aren't limited to HTTP), WAS allows you to choose the most appropriate protocol for your needs.
A WCF service hosted in WAS works similarly to an ASMX Service. For the HTTP protocol, it relies on the ASP.NET HTTP pipeline to transfer data. For non-HTTP protocols such as TCP and Named Pipes, WAS leverages the extensibility points of ASP.NET to transfer data. These extensibility hooks are implemented in the form of protocol handlers that manage communication between the worker process and the Windows service that receives incoming message. There are two types of protocol handlers: Process Protocol Handler (PPH) and App Domain Protocol Handler (ADPH). When the WAS activates a worker process instance, it first loads the required process protocol process handlers and then the the app domain protocol handlers.
What You Need |
|
Setting up WAS
Before getting into the steps involved in setting up WAS, create a new WCF Service project named WASHostedService through Visual Studio 2005. I've used C# for the examples here, but you can easily translate them to VB.NET.
In Windows Vista, you need to perform two steps to host WCF services in WAS. First, install the WCF Non-HTTP activation components. To do that, go to the Start menu —> Control Panel —> Programs and Features, and then click "Turn Windows Components On or Off" in the left pane. Expand the Microsoft .NET Framework 3.0 node and ensure that the "Windows Communication Foundation Non-HTTP Activation" feature is checked as shown in Figure 1.
Figure 1. WAS Hosting for Non-HTTP Protocols:
To make your WCF services available for remote invocation through TCP, Named Pipe and MSMQ protocol bindings, turn on the WCF Non-HTTP Activation feature through the Windows Features dialog box.
如果使用Win 7则,则配置窗口大致如下
Second, to use a non-HTTP protocol such as TCP or Named Pipes, you need to add the site binding to the WAS configuration. As an example, here's how you'd bind the default web site to the TCP protocol. Go to the Start menu —> Programs —>Accessories. Right click on the "Command Prompt" item, and select "Run as administrator" from the context menu. You'll see a command prompt that has the requested elevated administrator permissions so you can execute administrator commands. Execute the following command:
<DriveName>\Windows\system32\inetsrv\appcmd.exe set site "Default Web Site" -- +bindings.[protocol='net.tcp',bindingInformation='808:*']
That command adds the net.tcp site binding to the default web site by modifying the applicationHost.config file located in the <DriveName>\Windows\system32\inetsrv\config directory.
After binding the default web site to the appropriate protocol, you need to enable the individual web applications to support the same protocol. To enablenet.tcp for the WASHostedService site, run the following command from an administrator-level command prompt:
%windir%\system32\inetsrv\appcmd.exe set app "Default Web Site/MyProjects/DevX/WASHostedService" /enabledProtocols:http,net.tcp
Now that you have set up the web site and application, you are ready to create a service and host it in WAS.
Creating the Service
To start, add a service named HelloWorldService.svc to the WASHostedService project. The newly added HelloWorldService.svc contains the following lines of code.
<%@ ServiceHost Language="C#" Debug="true" Service="HelloWorldService" CodeBehind="~/App_Code/HelloWorldService.cs" %>
Note that the HelloWorldService.svc has a code-behind file named HelloWorldService.cs that Visual Studio places in the App_Code directory. Open up the HelloWorldService.cs file and modify its code as follows:
using System; using System.ServiceModel; [ServiceContract()] public interface IHelloWorldService { [OperationContract] string HelloWorld(string input); } public class HelloWorldService : IHelloWorldService { public string HelloWorld(string input) { return "Hello: " + input; } }
The preceding code decorates the interface IHelloWorldService definition with the [ServiceContract] attribute to indicate that this interface contains the service operation definitions. To expose the individual methods in the interface as service operations, you specify the [OperationContract] attribute. After defining the service contract in an interface, you can then implement the methods inside the actual class—HelloWorldService in this case.
After creating the service, you need to specify the service behavior in the configuration file. Configuring the service behavior in an external configuration file lets you customize the service behavior without having to modify and recompile the service code. To host the HelloWorldService in WAS, modify the Web.configfile in the service project as follows:
<?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <service name="HelloWorldService" behaviorConfiguration="HelloWorldServiceBehavior"> <endpoint binding="netTcpBinding" bindingConfiguration="PortSharingBinding" contract="IHelloWorldService" /> <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" /> </service> </services> <bindings> <netTcpBinding> <binding name="PortSharingBinding" portSharingEnabled="true"> <security mode="None" /> </binding> </netTcpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="HelloWorldServiceBehavior"> <serviceMetadata /> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
Through its attributes, the <service> element under <system.ServiceModel>\<services> specifies the name of the service as well as the name of the behavior configuration that you want to use to control the service's behavior. The <service> element also contains another child element named <endpoint>where you specify the address, contract, and binding for the service. Note that the contract attribute is set to the name of the interface—IHelloWorldService. To expose the service through TCP binding, set the binding attribute to netTcpBinding. Finally, the separate <netTcpBinding> element defines specific characteristics of the TCP binding, such as security.
Creating the Client
To test the HelloWorld service, create a new Visual C# Windows Forms application and name it WASHostedServiceClient.
Next, you'll need to create a proxy for the WCF service described earlier in this article. You'll also need to create a configuration file containing the settings required to connect to the service. You can accomplish both tasks through the Service Model Metadata Utility (svcutil.exe), which builds a proxy and corresponding configuration file based on a published service's metadata. For example, here's the command to run svcutil.exe to create a proxy and configuration file for the HelloWorldService:
svcutil.exe net.tcp://localhost/MyProjects/DevX/ WASHostedService/HelloWorldService.svc/mex
Figure 2 shows the output produced by the preceding command.
Figure 2. Svcutil.exe Output:
The Svcutil.exe utility downloads a service's WSDL file using that and related service metadata to create a client side proxy and configuration file.
The output from Figure 2 has two files:
- A WCF proxy (a C# class file in this case) that translates method calls to messages dispatched to the service.
- An output.config file (with the settings based on the service configuration) that clients can use to communicate with the service.
Now add the created proxy file to the WASHostedServiceClient project. Also rename the output.config file created with svcutil to App.config and add that to the WASHostedServiceClient project as well. The App.config file contains a number of configuration entries related to the invocation behavior of the client. The following code highlights the important sections of the App.config file:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <bindings> <netTcpBinding> <binding name="NetTcpBinding_IHelloWorldService" -------- </binding> </netTcpBinding> </bindings> <client> <endpoint address= "net.tcp://thiru-pc/MyProjects/ DevX/WASHostedService/HelloWorldService.svc" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IHelloWorldService" contract="IHelloWorldService" name="NetTcpBinding_IHelloWorldService" /> </client> </system.serviceModel> </configuration>
The <system.ServiceModel> element is the root of the service client configuration section. Inside that are the <bindings> and <client> elements where you specify the binding details and endpoint details respectively.
At this point, you are ready to consume the service by writing code against the proxy. To do that, add a command button named btnHelloWorld to the form and modify its Click event-handling code as follows:
private void btnHelloWorld_Click(object sender, EventArgs e) { HelloWorldServiceClient client = new HelloWorldServiceClient(); MessageBox.Show(client.HelloWorld("Thiru")); }
The implementation simply invokes the HelloWorld() method of the HelloWorldService using the proxy class (generated through the svcutil utility) from the previous section and displays the results of the invocation via a message box.
You've seen the steps involved in using TCP binding to host the service in WAS. The next section discusses how to use Named Pipe binding to host a service in WAS.
Using Named Pipe Activation
As part of the implementation of this service, it's important to understand the basics of data contracts and their role in returning complex type data from the service.
Just as in the previous example, you first need to bind the net.pipe protocol to the default web site. Use the following command from an elevated administrator command prompt.
<DriveName>\Windows\system32\inetsrv\appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.pipe', bindingInformation='*']
Then enable the named pipe activation for the WASHostedService virtual directory as follows:
<DriveName>\Windows\system32\inetsrv\appcmd.exe set app "Default Web Site/MyProjects/DevX/WASHostedService" /enabledProtocols:http,net.pipe
The preceding command enables net.pipe support for the WASHostedService application.
You define a data contract by decorating a class, structure, or enumeration with the [DataContract] attribute and identifying the members by placing[DataMember] attributes on the fields or properties of the class. Here's an example. Add a new class file named Product.cs to the WASHostedServiceproject and modify its code as follows:
using System; using System.Runtime.Serialization; [DataContract] public class Product { [DataMember] public int ProductID; [DataMember] public string Name; [DataMember] public string ProductNumber; }
You can leverage the data contract from a WCF service. Add a WCF service named ProductService.svc to the project and modify its code-behind file as shown in Listing 1:
The GetProductByProductID() method in Listing 1 is straightforward. It retrieves a connection string from the Web.config file, opens a database connection, creates a SQL command string and a SqlCommand object, and executes the query against the database using theSqlCommand.ExecuteReader() method. It loops through the data returned in the resultant SqlDataReader object, filling a new Product object with the retrieved values, then returns that to the client.
VB.NET Listing 1. The ProductService Service: The listing contains the complete code for the ProductService, which returns product details given a ProductID. using System; using System.Data; using System.Data.SqlClient; using System.ServiceModel; [ServiceContract()] public interface IProductService { [OperationContract] Product GetProductByProductID(int productID); } public class ProductService : IProductService { public Product GetProductByProductID(int productID) { string connectionString = System.Web.Configuration. WebConfigurationManager.ConnectionStrings ["AdventureWorks"].ConnectionString; Product prod = new Product(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "Select ProductID, Name, ProductNumber " + " from Production.Product Where ProductID = " + productID.ToString(); SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader (CommandBehavior.CloseConnection); while (reader.Read()) { prod.ProductID = (int)reader["ProductID"]; prod.Name = (string)reader["Name"]; prod.ProductNumber = (string)reader["ProductNumber"]; } } return prod; } }
To configure the Named Pipe binding for this service, add the <service> section shown below directly underneath the<system.serviceModel>/<services> element in the app.config file:
<service name="ProductService" behaviorConfiguration="ProductServiceBehavior"> <endpoint binding="netNamedPipeBinding" bindingConfiguration="Binding1" contract="IProductService" /> <endpoint address="mex" binding="mexNamedPipeBinding" contract="IMetadataExchange" /> </service>
The configuration sets the behaviorConfiguration and binding values to ProductServiceBehavior and netNamedBinding respectively. You can define these (starting with NetNamedPipeBinding) by adding the following lines of code directly underneath the <system.serviceModel>/<bindings>section as shown below:
<netNamedPipeBinding> <binding name="Binding1" > <security mode = "None"> </security> </binding > </netNamedPipeBinding>
Finally, define the ProductServiceBehavior by adding the following <behavior> section to the<system.serviceModel>/<behaviors>/<serviceBehaviors> section.
<behavior name="ProductServiceBehavior"> <serviceMetadata /> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior>
That's all you have to do to support Named Pipe binding from the service side.
Consuming the Product Service
From the client side, just as in the previous example, the first step in consuming a service is to create a proxy and configuration file for the client. Again, you use svcutil.exe. For the ProductService, you can accomplish that with the following line of code from the command prompt.
svcutil.exe net.pipe://localhost/MyProjects/DevX/ WASHostedService/ProductService.svc?WSDL
That creates a proxy file and a configuration file. Add the created proxy file to the WASHostedServiceClient project. From the output.config file, copy the <netNamedPipeBinding> and <endpoint> sections to the App.config file. I've highlighted these sections in the output.config file shown below:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <bindings> <netNamedPipeBinding> <binding name="NetNamedPipeBinding_IProductService" -------- </binding> </netTcpBinding> </bindings> <client> <endpoint address="net.pipe://thiru- pc/MyProjects/DevX/WASHostedService/ProductService.svc" binding="netNamedPipeBinding" bindingConfiguration= "NetNamedPipeBinding_IProductService" contract="IProductService" name="NetNamedPipeBinding_IProductService" /> </client> </system.serviceModel> </configuration>
To test the service, add a command button named btnGetProduct and a list box named lstResults to the form and modify the button's Click event as follows:
private void btnGetProduct_Click( object sender, EventArgs e) { ProductServiceClient client = new ProductServiceClient(); Product prod = client.GetProductByProductID (Convert.ToInt32(txtProductID.Text)); lstResults.Items.Clear(); lstResults.Items.Add(prod.ProductID.ToString()); lstResults.Items.Add(prod.Name); lstResults.Items.Add(prod.ProductNumber); }
The preceding code passes in a user-entered ProductID value to the service, which retrieves the product details and returns a Product object. Finally, it displays the product detail results in the list box. Figure 3 shows the output produced by the Windows form.
Figure 3. Testing the ProductService:
When you enter a product id in the text box and click on the Get Product button, the Windows form invokes the GetProductByProductID() method to get the product details and displays the results in the list box control.
This article showed you the steps involved in using WAS to host WCF services and examples of how to use TCP and Named Pipe bindings to host and consume the WCF services. You've seen how to use some key WCF concepts—including the use of configuration files—to define the service behavior. To consume the services, you saw how to use the Service Model Metadata Utility (svcutil.exe) to create proxies and configuration, both for simple data types and for more complex types that require data contracts. All in all, WAS is both a more powerful and more flexible host for WCF services than IIS, and is a welcome addition to developers' toolkits.