Hosting WCF application in a console application

In our earlier article http://assertonexception.blogspot.com/2009/07/wcf-article-1-introduction.html, we see how the Self Hosting is working. Now lets see how we can host a WCF application.
  1. Open Visual Studio
  2. Click File -> New -> Project -> Visual C# -> WCF and then select WCF Library.
  3. Add another console application project in the same solution. (File -> Add -> New Project -> Visual C# -> Windows -> Console Application)
  4. Add Application Configuration file into the console application (Project -> Add New Item -> Application Configuration File)
  5. Move the content from WCF Library's App.config file to the App.config file in the Console application.
  6. Delete the App.config from WCF Librar y project.
  7. Build the WCF Library Project.
  8. Add project reference of WCF Library project to the Console Application.
  9. Add System.ServiceModel reference to the Console application.
  10. Add the following code.

namespace My_Samples
{
    using System;
    using System.ServiceModel;
    // WCF service library that we created earlier.
    using MyServiceLibrary;

    class Program
    {
        static void Main(string[] args)
        {
            try
            {

                ServiceHost host = new ServiceHost(typeof(MyService));
                host.Open();
                Console.WriteLine("Service Started...Hit 'ENTER' to stop the service...");
                Console.ReadLine();
                if (host.State != CommunicationState.Faulted)
                    host.Close();

            }
            catch (TimeoutException timeProblem)
            {
                Console.WriteLine(timeProblem.Message);
            }
            catch (CommunicationException commProblem)
            {
                Console.WriteLine(commProblem.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }
    }
}
  1. Run the console application. Now your service is started listening on the URL mentioned in the app.config file of your console application.

No comments:

Post a Comment