Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Hosting WCF Service

0.00/5 (No votes)
18 Jul 2015 1  
Hosting WCF Service - Self Hosting

Introduction

Windows Communication Foundation (WCF) Services can be hosted in the following ways:

  1. Self-Hosting
  2. Windows Service
  3. Internet Information Services (IIS)
  4. Windows Activation Services (WAS)

Multiple hosting and protocols supported by WCF.

Hosting Environment Supported protocol
Windows console and form application HTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services) HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6 http, wshttp
Web server IIS7 - Windows Process Activation Service (WAS) HTTP,net.tcp,net.pipe,net.msmq

A summary of hosting options and supported features.

Feature Self-Hosting IIS Hosting WAS Hosting
Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startup Message-based Message-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes

Selecting the right hosting environment for your services is a choice driven largely by deployment requirements related to transport protocol and operating platform.

In this example, I will show, Self-Hosting method to consume a WCF service.

Using the code

Our sample application performs the simple integer arithmetic operations.

  1. Create a WCF service
  2. Create a console application to perform arithmetic operations.
  • IDE - Visual Studio 2013

Part 1 : Create WCF service

1. Open Visual Studio 2013

2. Go to File menu-> New -> Project

3. Select Installed -> Templates -> Visual C# ->WCF then select "WCF Service Application" and give name "SelfHostingTest"

4. Open IService1.cs file and delete the existing DataContract details, then add a new ExceptionMessage DataContract to show the exception details.

[DataContract]
public class ExceptionMessage
{
    private string infoExceptionMessage;
    public ExceptionMessage(string Message)
    {
        this.infoExceptionMessage = Message;
    }
    [DataMember]
    public string errorMessageOfAction
    {
        get { return this.infoExceptionMessage; }
        set { this.infoExceptionMessage = value; }
    }
}

5. Delete all the OperationContract listed in the interface IService1, then add new OperationContracts with FaultContract to do the arithmetic operations.

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(ExceptionMessage))]
    int Addition(int number1, int number2);

    [OperationContract]
    [FaultContract(typeof(ExceptionMessage))]
    int Subtraction(int number1, int number2);

    [OperationContract]
    [FaultContract(typeof(ExceptionMessage))]
    int Multiplication(int number1, int number2);
        
    [OperationContract]
    [FaultContract(typeof(ExceptionMessage))]
    int Division(int number1, int number2);
}

6. Expand Service1.svc file and open Service1.svc.cs file. Remove all the function inside the Service1 class. Here we are going to implement the interface methods.

  • Add the following code to Addition() method
public int Addition(int number1, int number2)
{
    try
    {
        return number1 + number2;
    }
    catch (Exception exception)
    {
        throw new FaultException<exceptionmessage>(new ExceptionMessage(exception.Message));
    }
}
</exceptionmessage>
  • Add the following code to Subtraction() method
public int Subtraction(int number1, int number2)
{
    try
    {
        if (number1 > number2)
        {
            return number1 - number2;
        }
        else
        {
            return 0;
        }
    }
    catch (Exception exception)
    {
        throw new FaultException<exceptionmessage>(new ExceptionMessage(exception.Message));
    }
}
</exceptionmessage>
  • Add the following code to Multiplication() method
public int Multiplication(int number1, int number2)
{
    try
    {
        return number1 * number2;
    }
    catch (Exception exception)
    {
        throw new FaultException<exceptionmessage>(new ExceptionMessage(exception.Message));
    }
}
</exceptionmessage>
  • Add the following code to Division() method
public int Division(int number1, int number2)
{
    try
    {
        if (number2 != 0)
        {
            return number1 / number2;
        }
        else
        {
            return 1;
        }
    }
    catch (Exception exception)
    {
        throw new FaultException<exceptionmessage>(new ExceptionMessage(exception.Message));
    }
}
</exceptionmessage>

7. Finally we created the WCF service for Self-Hosting and Build it.

Part 2 : Create console application

1. Right click on the solution -> Add ->New Project

2. Select Console Application and Create.

3. Add the "SelfHostingTest" reference and add "System.ServiceModel" assembly.

4. Right click the "App.config" file of console application, then select "Edit WCF Configuration".

5. It will show a pop up to configure.

6. Select the "Services" folder then click on the right side link "Create a New Service". Click on the Browse Button and open the bin folder of "SelfHostingTest". Select "SelfHostingTest.dll" and click "Open". In the next window, It will show our service. select the service and click "Open".

7. Click on the Next button, it will ask to provide the Service Contract

8. Click on the Next button, it will ask to select the binding. In our demo we are going to use "TCP".

9.  Click on the next button, it will ask th endpoint address. Enter the relative address of "SelfHostingTest" service.

10. Click on the next button, it will show all the features we selected previously.

11. Click on finish button, it will show our service.

12. Here we need to expand our service and select "Host".

13. Here we are going to add two base addresses, one for the service endpoint and another one to enable metadata exchange. Add base address by clicking "New" button.

14. We need to enable service behaviours to enable metadata exchange, clients can generate proxy classes using that. Expand the "Advanced" folder then select the "Service Behaviour" option the click "New Service Behavior Configuration".

15. Change service behavior name to "SelfHostingBehavior".

16. We need to add a new service behaviour for metadata exchange. Select "SelfHostingBehavior" then select the "Add" button then select from the list "ServiceMetadata".

17. Then click on "serviceMetatdata" to set "HttpGetEnable" to "True".

18. We need to set this new behavior to our service. For that click on our "SelfHostingTest" service and set the "Behaviour Configuration" to "SelfHostingBehavior".

19. Click File menu and save, then close this window. Then it will ask for you to save the changes; click Yes.

20. Now check App.config file, all the previous setup details automatically provided in the App.config file.

 

21. Open Console Application Progarm.cs file and add the following codes.

  • Include the following using statements.
using SelfHostingTest;
using System.ServiceModel;
  • Add a new function WCFServiceConsume()
public static void WCFServiceConsume()
{
    try
        {
            Console.WriteLine("Self-Hosting a WCF Service in Console Application\n");
            Console.WriteLine("-------------------------------------------------\n");
            Console.WriteLine("Enter first integer number : ");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter second integer number : ");
            int number2 = Convert.ToInt32(Console.ReadLine());
            SelfHostingTest.Service1 wcfService = new SelfHostingTest.Service1();

            try
            {
                int addition = wcfService.Addition(number1, number2);
                Console.WriteLine("Addition Result : " + addition);
            }
            catch (FaultException<exceptionmessage> exceptionFromService)
            {
                Console.WriteLine("Addition Service Error : " + exceptionFromService.Detail.errorMessageOfAction);
            }

            try
            {
                int subtraction = wcfService.Subtraction(number1, number2);
                Console.WriteLine("Subtraction Result : " + subtraction);
            }
            catch (FaultException<exceptionmessage> exceptionFromService)
            {
                Console.WriteLine("Subtraction Service Error : " + exceptionFromService.Detail.errorMessageOfAction);
            }

            try
               {
                int multiplication = wcfService.Multiplication(number1, number2);
                Console.WriteLine("Multiplication Result : " + multiplication);
            }
            catch (FaultException<exceptionmessage> exceptionFromService)
            {
                Console.WriteLine("Multiplication Service Error : " + exceptionFromService.Detail.errorMessageOfAction);
            }

            try
            {
                int division = wcfService.Division(number1, number2);
                Console.WriteLine("Division Result : " + division);
            }
            catch (FaultException<exceptionmessage> exceptionFromService)
            {
                Console.WriteLine("Division Service Error : " + exceptionFromService.Detail.errorMessageOfAction);
            }
            Console.WriteLine("*********************************\n");
        }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
    }
    finally
    {
        ConsoleClose();
    }
}
</exceptionmessage>
  • Add a new function ConsoleClose()
public static void ConsoleClose()
{
    Console.WriteLine("Are you sure to close the application? (1/0)\n");
    string close = Console.ReadLine();
    if (close == "1")
    {
        Console.Clear();
        WCFServiceConsume();
    }
}
  • Call the WCFServiceConsume() function in main method
static void Main(string[] args)
{
    WCFServiceConsume();
}

 

22. Set Console application as the Start up project.

23. Run the application.

Output

  • Successfull execution

  • Error handling

History

1st Version : 2015-07-18

2nd Version : 2015-07-19

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here