Feb
17
2012

C#.Net How To: Self Host a WCF Service in Visual Studio 2010

In this WCF tutorial let’s learn to self host a WCF service. We learned from the earlier wcf tutorials, that a WCF service can be hosted in IIS, Managed Windows Services, Windows Activation Service (WAS) and It also supports Self-hosting. WCF hosting in IIS and Windows service i have already explained.

What is Self-hosting?

Self-hosting is nothing but hosting a service in a managed Application which is the most flexible option because it requires the least infrastructure to deploy the service. But self-hosting is also the least robust hosting option, because managed application do not provide the advanced hosting management features like IIS and Windows service does.

What does self-hosting of WCF service means? The answer is WCF provides the user to host the service in any application that could be Console Application or Windows forms etc. Developer is responsible for providing and managing the life cycle of the host process unlike IIS and Windows Services. Client and Service can be in the same process in Self-hosting.

Steps to self host a WCF Service in Console Application

The following tutorial demonstrates the steps to host a WCF Service in Console Application that takes input as a string (i.e. name) and returns a Welcome message like – “Welcome to http://www.a1ashiish-csharp.blogspot.in , Mr. Ashish Ramteke“.

  1. Open VS 2010 and create a new console application project. Go to File menu-> New -> Project… Select Console Application and specify a project name. In this C# tutorial the name of the Console application is kept as WCFSelfHostedService.
    Console application to self host a WCF service
    Self Host a WCF Service – Creating console application

    Click on OK button to proceed further.

  2. Now add System.ServiceModel.dll in this project. It contains the classes, enumerations and interfaces necessary to build the service and client applications that can be used to build wildly distributed applications. To add the System.ServiceModel.dll goto Solution Explorer, right click the project name “WCFSelfHostedService” and select “Add reference”.
    Adding Reference to Self host a WCF service
    Self Host WCF Service – Adding Reference
  3. Select System.ServiceModel from .Net tab and click on OK button.
    Reference System.ServiceModel
    Reference System.ServiceModel for Self host WCF service
  4. In this we are going to implement a WCF service. To create a WCF service we need to define and implement the service contract. To accomplish this create a new Interface. To create a new interface goto Solution Explorer, right click on project name “WCFSelfHostedService“, select Add and New Item..
    Adding Interface to Self host WCF service
    Adding Interface for Self host WCF service
  5. Select Interface, name it “IWCFSelfHostedService” and click on ADD button.
    Self host WCF service Interface
    Interface for Self host WCF service
  6. As soon as you create a new interface an auto-generated code would appear in your IWCFSelfHostedService.cs file as shown below –
    Self host WCF Interface Auto Generated Code
    Self host WCF service Interface Auto Generated Code
  7. Now define the service contract and operation contract in this interface to self host a wcf service. To add service contract to service add following line to top of the file –
    using System.ServiceModel;

    After defining service contract and operation contract the final code would look a like –

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    namespace WCFSelfHostedService
    {
        [ServiceContract]
        public interface IWCFSelfHostedService
        {
            [OperationContract]
            String WelComeMessage(String name);
        }
    }

    Now, the next step is to implement the ServiceContract.

  8. Goto Solution Explorer, right click on project “WCFSelfHostedService“, goto Add, select “Class” and name it “WCFSelfHostedService.cs“.
    Add following lines at the top of the file –

    using System.ServiceModel;
    using System.ServiceModel.Description;

    After implementing service contract the final code would look a like to self host a wcf service

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    namespace WCFSelfHostedService
    {
        public class WCFSelfHostedService : IWCFSelfHostedService
        {
            public String WelComeMessage(String name)
            {
                return String.Format(“Welcome to http://www.csharptutorial.in, {0}”, name);
            }
        }
    }

    The service contract implementation is done. The next step is to create an instance of the ServiceHost class. ServiceHost is the core class to host the WCF service. ServiceHost accepts the implemented contract class and base address as contract operator.

  9. Goto Program.cs file and at the top of the main method create the instance of an URI class with the base address for the service.
    Uri baseServiceAddress = new Uri(“http://localhost:8090/Welcome”);

    Now, create the instance of a ServiceHost class, passing the Type that represents the base address Uniform Resource Identifier (URI) to the ServiceHost. Call the Open method on the ServiceHost to initialize the service and prepare it to receive the messages.
    Below code shows the complete implementation of the host process.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    namespace WCFSelfHostedService
    {
        public class Program
        {
            static void Main(string[] args)
            {
                // Base address
                Uri baseServiceAddress = new Uri(“http://localhost:8090/Welcome”);
                using (var host = new ServiceHost(typeof(WCFSelfHostedService), baseServiceAddress))
                {
                    // Enable MetaData publishing.
                    ServiceMetadataBehavior serviceMetaDataBehaviour = new ServiceMetadataBehavior();
                    serviceMetaDataBehaviour.HttpGetEnabled = true;
                    serviceMetaDataBehaviour.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                    host.Description.Behaviors.Add(serviceMetaDataBehaviour);
                    // Open the ServiceHost to start listening for messages. No endpoint are explicitly defined, runtime creates default endpoint.
                    host.Open();
                    Console.WriteLine(“The service is ready at {0} and host at {1}”, baseServiceAddress, DateTime.Now.ToString());
                    Console.WriteLine(“The service and client is running in the same process.”);
                    WCFSelfHostedService selfHostService = new WCFSelfHostedService();
                   
                    Console.Write(“Enter your name. : “);
                    Console.WriteLine(selfHostService.WelComeMessage(Console.ReadLine()));
                    Console.WriteLine(“Host is running… Press <Enter> key to stop the service.”);
                    Console.ReadLine();
                    //Close the service.
                    host.Close();
                }
            }
        }
    }

    Your Self-hosted WCF service is ready to use now.

  10. Save all files, build the solution and execute the application to run the Service. Press Ctrl+F5 to execute the service and output like below screen would appear –
    Running Self hosted WCF service
    Running Self hosted WCF service
  11. Now your self hosted service is running. You can test the service by entering http://localhost:8090/Welcome in internet browser. You can quickly test the service by the help of WcfTestClient utility. Follow my previous post on how to test WCF service using WcfTestClient.

In this wcf tutorial, the wcf service is consumed in the same application it means the service and client both are running at the same process. If you want to consume the service in some other console application then do not write the yellow highlighted part and follow my previous article on how to consume the service in console application.

I hope you enjoyed the article. If you find this article helpful, then could you please share the article on your social media?

More related articles…

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

7 Comments+ Add Comment

  • खुप छान ….. आशिष ….

    धन्यवाद….

    – अभिजीत

  • Thanks for starting this up. This blog is something that is needed on the web someone with a little originality. hostinghq.ca

  • Thank you so much for your blogs!
    I am new to my job and as part of the training, I was tasked to deliver reports on different tpoics including Web Services and WCF. I googled for sources and came across your site. Once I got here, i really didnt care to search for another source. I have everything I need here. Thanks, I just finished my reports. Please continue to share your knowledge.

    • nylsirk, Thank you so much for your appreciation..!!
      Share the blog with your friends so that it would reach to right person like you and me…!!! :)

  • Thanks! I am really glad the blog helped you!

  • thank u for great wcf example for beginners ..

Leave a comment