Tuesday, 16 July 2013

WCF Self Hosting with Example and Source Code








Introduction

Windows Communication Foundation (WCF) is a programming interface as part of .NET Framework.

Using 3 types we can host service in WCF
1          1. Self-Hosting
2           2 .IIS Hosting
3          3. WAS


In this article I will tell you how to create WCF Service and how to host using self-hosting and how to consume this service in Web Application. In this article I will discuss about self-hosting your WCF Service, because it’s the most flexible and easiest way to host WCF services. Another way to host WCF Service is using Internet Information Services(IIS). IIS will be explained in my other article.



Download Source Code



Part-1   Create the Service

Open Visual Studio 2010 

Step 1: Select the new Empty Solution and give name WCFProject.


Step 2: Then add new Class Library Project and give name SaleClassLibrary.

Step 3: Then add reference of System.ServiceModel and System.Runtime.Serialization into that project.

Step 4: Then add new Interface ISaleService.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;

 [ServiceContract]
    interface ISaleService
    {
        [OperationContract]
         bool InsertCustomer(Customer obj);

        [OperationContract]
        List<Customer> GetAllCustomer();

        [OperationContract]
        bool DeleteCustomer(int Cid);

        [OperationContract]
        bool UpdateCustomer(Customer obj);    
    }

  [DataContract]
   public class Customer
    {
        [DataMember]
        public int CustomerID;
        [DataMember]
        public string CustomerName;       
        [DataMember]
        public string Address;
        [DataMember]
        public string EmailId;
    }
Step 5: And write the following code in the SaleService.cs file: 

SaleService.cs page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class SaleService : ISaleService
    {
        public bool InsertCustomer(Customer obj)
        {
            cutomerList.Add(obj);
            return true;
        }

        public List<Customer> GetAllCustomer()
        {
            return cutomerList;
        }

        public bool DeleteCustomer(int Cid)
        {
            var item = cutomerList.First(x => x.CustomerID == Cid);

            cutomerList.Remove(item);
            return true;
        }

        public bool UpdateCustomer(Customer obj)
        {
            var list = cutomerList;
            cutomerList.Where(p => p.CustomerID ==
            obj.CustomerID).Update(p => p.CustomerName = obj.CustomerName);
            return true;
        }

      public static  List<Customer> cutomerList = new List<Customer>()
         {
        new Customer {CustomerID = 1, CustomerName="Sujeet",
        Address="Pune", EmailId="test@yahoo.com" },
        new Customer {CustomerID = 2, CustomerName="Rahul",
        Address="Pune", EmailId="test@yahoo.com" },
        new Customer {CustomerID = 3, CustomerName="Mayur",
        Address="Pune", EmailId="test@yahoo.com"}
         };

      
   

Step 6: Build your Class library.

Step 7: Add new Console Application in the same solution SaleServiceSelfHosting



Step 8: In this project Add reference of the WCF Class library project and Add reference of System.ReferenceModel Namespace.

Step 9: Add below code on Console Application
class Program
    {
        static void Main(string[] args)
        {

            Uri baseAddress = new Uri("http://localhost:6525/SaleService");

            using (ServiceHost host = new ServiceHost(typeof(SaleClassLibrary.SaleService), baseAddress))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                host.Open();

                Console.WriteLine("The service is ready at: {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service");
                Console.ReadKey();
                host.Close();

            }
        }
    }

Step 10: Build your Console application and set as startup project and run the project.

Your self-hosting WCF Service is now running 


WCF Self-Hosting

WCF come with ServiceHost class that makes you can host your services in your own application easily. With WCF what you need to do is just configuring your service endpoint and calling the .open() method of ServiceHost.



Advantages & Disadvantage
To be able to host WCF service you need WCF runtime and .NET application where you want to host your service.

Advantages:
   Easy: This way of hosting don’t need many lines of code to successfully run
   Flexible: You can easily decide when your service active by calling the .open() and .close() method.

Disadvantage
However, this self-hosting method has some disadvantage. This self-hosting service is reachable only when the application that hosts the service is running. So, self-hosting is only suitable when the development and demonstration phase of your system.

Happy Programming!!

If you have any query mail me to Sujeet.bhujbal@gmail.com     


Regards

Sujeet Bhujbal

------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------

3 comments :

Kushal Suyal said...

Very good article and example...
Now I understood WCF self hosting...
Thank you very much...
Also, in your article, add how to consume self-hosted service in a web application (as you consumed WCF service in sample code)

Sujit Bhujbal said...

Thanks Kushal ...

robert robinson said...

I also wonder how one should evaluate one's experience as a cheap web hosting of a town one doesn't particularly like. Because equally, it could mean that the residential experience is actually a lot better than the tourist one.

Post a Comment