Click here to Skip to main content
15,907,326 members
Articles / Programming Languages / C#
Tip/Trick

Hosting WCF Service

Rate me:
Please Sign up or sign in to vote.
3.82/5 (5 votes)
18 Jul 2015CPOL4 min read 19K   199   18   8
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.

C#
[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.

C#
[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
C#
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
C#
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
C#
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
C#
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.

Image 1

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".

Image 2

Image 3

Image 4

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

Image 5

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

Image 6

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

Image 7

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

Image 8

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

Image 9

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

Image 10

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.

Image 11

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".

Image 12

15. Change service behavior name to "SelfHostingBehavior".

Image 13

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".

Image 14

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

Image 15

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".

Image 16

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.

Image 17

 

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()
C#
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></exceptionmessage></exceptionmessage></exceptionmessage>
  • Add a new function ConsoleClose()
C#
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
C#
static void Main(string[] args)
{
    WCFServiceConsume();
}

 

22. Set Console application as the Start up project.

23. Run the application.

Output

  • Successfull execution

Image 18

  • Error handling

Image 19

History

1st Version : 2015-07-18

2nd Version : 2015-07-19

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionAbout code Pin
Ghost Basenji30-Aug-15 14:26
Ghost Basenji30-Aug-15 14:26 
AnswerRe: About code Pin
Math08avan31-Aug-15 9:29
Math08avan31-Aug-15 9:29 
SuggestionPictures Pin
tommasuth20-Jul-15 6:37
professionaltommasuth20-Jul-15 6:37 
Please add the Pictures. They are not visible.
Generalpictures are not visible Pin
Southmountain18-Jul-15 9:15
Southmountain18-Jul-15 9:15 
GeneralRe: pictures are not visible Pin
Math08avan18-Jul-15 19:52
Math08avan18-Jul-15 19:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.