Self Hosting a WCF service

As we know WCF supports various hosting options. Self Hosting is one of them.
What is Self Hosting?
WCF allows hosting a service in an application such as Console Application.


  1. Create a Console Application Project to host a WCF Service. 
  2. Add WCF Service project Reference in this Console Application. 
  3. Delete existing App.config file. 
  4. Add new App.config file. 
  5. Rightclick on App.Config and select Edit WCF Configuration.
WCF service Self Host

6. Click “Create new Service ”

WCF service Self Host

7. Browse for Bin->Debug location (Make sure you have built the console application successfully.)

WCF service self hosting

8.
WCF service Self Host
         
9.
WCF service Self Host

10.

         WCF service Self Host

11.
WCF service Self Host
  
12. Click on New and add 2 address.  WCF service Self Host

13. Now go for Service Behavior
WCF service Self Host
       
14. Click on Add and select serviceMetaData

WCF service Self Host
      
15. Select serviceMetaData from left side and set HttpGetEnabled to True.

WCF service Self Host
      
16. Select Service name from left side and select BehaviorConfiguration from drop down. Refer highlighted section in below screen.

WCF service Self Host
     
17. Now close the WCF Config Editor, and it will prompt to save. Save it.
18. Now your new App.Config file will look like this.

WCF service Self Host
19. Now write code in Program.cs

static void Main(string[] args)
        {
            using (ServiceHost myhost = new ServiceHost(typeof(WcfServiceLibraryMaster.Product)))
            {
                myhost.Open();
                Console.WriteLine("Host Started Successfully...");
                Console.ReadLine();
            }
        }

Now remember this is your service url:
WCF service Self Host

20. Now create a client to consume this WCF service. Add a service reference.

WCF service Self Host

21. Seems host is not running. Let’s start the host by running the project.

WCF service Self Host
       
22. The host is running now; let’s try to add service reference once again.
23. Now you can see, service was found.

WCF service Self Host

 24. Change the namespace to WCFSelfServiceRef and write below code.

WCFSelfServiceClient.WCFSelfServiceRef.ProductClient objClient = new WCFSelfServiceRef.ProductClient();
            string message = objClient.GetProduct(1001);
            Console.Write(message);
            Console.ReadLine();

25. Execute the code and you will see the output like below.

WCF service Self Host



Comments

Popular