Saturday, June 9, 2012

Hosting WCF Services in IIS

To host a WCF Service in IIS, you need a new physical file with the .svc extension. The file associates a service with its implementation and is the means for IIS to create ServiceHost for you. IIS takes over the interaction between your service and ServiceHost; you no longer have to instantiate and start ServiceHost yourself. The first line of the .svc file contains a directive enclosed in the ASP.NET <% Page %> directive that tells the hosting environment to which service this file points. The service code can then reside inline and it is a separate assembly registered in the GAC, in an assembly that resides in the application's Bin folder, or in a C# file that resides under the application's App_Code folder. The most common scenario is to define endpoints in a configuration file. In IIS, you have to define your endpoints in the Web.config file.

The most rich hosting option for WCF is IIS[ from IIS 7.0 onwords] and all hosting requirements for any good service is provided by IIS.

The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol.
Let as do some hands on, to create service and host in IIS

Step 1:Start the Visual Studio 2010 and click File->New->Web Site. Select the 'WCF Service' and Location as http. This will directly host the service in IIS and click OK.  
  •  Remove Service.cs,IService.cs and Service.svc from our IIHostingService Project



Step 2: I have created sample MyService service, which will display 'Hello Wolrd ' and returning "Service is running..". Interface and implementation of the Service is shown below.

write the following code under IMyService.cs


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

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMyService" in both code and config file together.
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetMessage();
}

 write the following code under MyService.cs

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

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MyService" in code, svc and config file together.
public class MyService : IMyService
{
            public void DoWork()
            {
            }

    public string GetMessage()
    {
        Console.WriteLine("Hello World");
        return "Service is running ";
    }
}
 Step 3: Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service.
 MyService.svc
<%@ ServiceHost Language="C#" Debug="true" 
Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>
Step 4: Server side configurations are mentioned in the config file. Here I have mention only one end point which is configured to 'wsHttpBinding', we can also have multiple end point with differnet binding. Since we are going to hosted in IIS. We have to use only http binding. We will come to know more on endpoints and its configuration in later tutorial. Web.Config
<system.serviceModel>
  <services>
   <service behaviorConfiguration="ServiceBehavior" name="MyService">
 <endpoint address="http://localhost/IISHostedService/MyService.svc" 
 binding="wsHttpBinding" contract="IMyService">
 <identity>
 <dns value="localhost"/>
 </identity>
 </endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
   </service>
 </services>
 <behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
 <!-- To avoid disclosing metadata information, 
 set the value below to false and remove the 
 metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true"/>
 <!-- To receive exception details in faults for 
 debugging purposes, set the value below to true.  
 Set to false before deployment to avoid disclosing exception information -->
 <serviceDebug includeExceptionDetailInFaults="false"/>
 </behavior>
   </serviceBehaviors>
  </behaviors>
</system.serviceModel>
Note: You need to mention the service file name, along with the Address mention in the config file. IIS Screen shot
                                    This screen will appear when we run the application.
 


 Step 5: Now we successfully hosted the service in IIS. Next we have to consume this service in client application. Before creating the client application, we need to create the proxy for the service. This proxy is used by the client application, to interact with service. To create the proxy, run the Visual Studio 2008 command prompt. Using service utility we can create the proxy class and its configuration information.
svcutil  http://localhost/IISHostedService/MyService.svc
                                  After executing this command we will find two file generated in the default location.
  • MyService.cs - Proxy class for the WCF service
  • Output.config - Configuration information about the service.
Step 6: Now we will start creating the Console application using Visual Studio 2010(Client application).
                                       
Step 7: Add the reference 'System.ServiceModel'; this is the core dll for WCF.
                            
Step 8: Create the object for the proxy class and call the HelloWorld method.
static void Main(string[] args)
        {
            //Creating Proxy for the MyService 
             MyServiceClient client = new MyServiceClient();
             Console.WriteLine("Client calling the service...");
             Console.WriteLine(client.HelloWorld("Ram"));
             Console.Read();

        }
Step 9: If we run the application we will find the output as shown below.
                    

No comments:

Post a Comment