Saturday, August 15, 2015

WCF Service hosting in IIS



Continuing with the series of discussion on the wcf services, we will now start with the discussion with options for hosting wcf services. We started with ABC of wcf service, then its contract types, further with the techniques to generate the proxy classes. Now we will focus on the hosting techniques. You can read the complete series on the links below:
  1. About the A.B.C. of WCF Service
  2. Types of Contracts in WCF
  3. WCF Proxy generation using 'Add reference'
  4. WCF Proxy generation using 'SvcUtil.exe'
  5. WCF Proxy generation using 'Channel Factory'
  6. WCF Proxy generation using 'Client Base'
There are multiple options for hosting a WCF service. These include the use of :

1. IIS Hosting
2. Self hosting
3. Windows Activation Service hosting
4. Windows Service hosting

In this article, we will discuss about the concept of IIS hosting. Hosting the wcf in IIS is same as that of hosting your web applications. So to start with, we add a new project of the type WCF service application and NOT wcf service library. There is a difference between the two. We will not get into the details of these two. So for now, let's simply add that project.


Next we remove any built in functions from the service interface and implementation, to add our simple method which can return a String value. So our service interface will look like below:


   namespace WCFIISHosting
   {
     [ServiceContract]
     public interface IService1
     {
         [OperationContract] 
         String GetString();
     }
   }




And our service implementation will become:

 
  namespace WCFIISHosting
  {
     public class Service1 : IService1
     {
         String IService1.GetString()
         {
             return "String from Service";
         }
     }
  }




So our service part is done. Now we need to simply host it in IIS. So start the IIS and add a new Application type, under the Default Website, by right clicking on it. See the screenshot below:




Provide a name to it and set the Physical Path to the root folder of the service code and click Ok. 



That's it, wcf is hosted now. Open the browser and browse the link:   

                                http://localhost/WCFIISHosting/Service1.svc



Now let's try to consume this any application. So for this, we add a new Console Application in the same solution and add it's service reference to the project.




Next, create the proxy instance and call the service method GetString() using it.

  
 namespace ConsoleApplciation1
 {
    class Program
    {
        static void Main(string[] args)
        {
            ServiceReference1Service1Client _obj = new ServiceReference1Service1Client();
            Console.Write(_obj.GetString());
            Console.ReadKey();
        }
    }
  }




Run the code and see the results. The results are available.




 Easy to host, isn't it. Happy coding...!!!

No comments:

Post a Comment