Next in our series of discussion about wcf services, we will now discuss the concept of self hosting a wcf service. If you have missed the previous articles, you can read them on the links below, which is complete series starting from ABC of wcf services till their hosting types:
In self hosting type of approach, the service can be hosted in any windows application or in a windows service.There is no use of IIS in this approach. So let's start with the code.
We create a new project named TestService. We remove all the default methods and add a simple method which takes two integer input parameters and returns their sum. So we have the following service contract.
- About the A.B.C. of WCF Service
- Types of Contracts in WCF
- WCF Proxy generation using 'Add reference'
- WCF Proxy generation using 'SvcUtil.exe'
- WCF Proxy generation using 'Channel Factory'
- WCF Proxy generation using 'Client Base'
- Hosting WCF Services in IIS
In self hosting type of approach, the service can be hosted in any windows application or in a windows service.There is no use of IIS in this approach. So let's start with the code.
We create a new project named TestService. We remove all the default methods and add a simple method which takes two integer input parameters and returns their sum. So we have the following service contract.
And our interface implementation will look like:
Next, in order to host the service, we add a new ConsoleApplication to the solution and call it as TestServiceHost. Also we need to add the service project reference to the console application project.
Now in order to host the service, when this console application starts, we will write the code in it's Main function. The code will be basically to define the ABC of the service, i.e. Address where service is, Binding to be used for communication and Contract to be used for communication. If you would like to know more about the ABC of WCF, then you can read it about here.
For this purpose, we will be using the ServiceHost class. So our code will be like the following:
That's it. Service is ready to be hosted now. Simply run the application and service is started.
In order to test the service, we will use the wcftestclient. Start the Visual Studio command prompt and type wcftestclient.exe. This will open the test client. Right click on My Service Projects and select Add Service. Enter the url of the service which we defined in the configuration in console application.
Double click on the GetSum method and provide the input parameters for a and b. Click Invoke and see the results.
And we have the results. So we can use any of the client applications instead of the wcftestclient. This can be any client application consuming the service using SOAP, by adding the reference or calling it through the ChannelFactory.
Hope you enjoyed reading it. Happy coding...!!!
No comments:
Post a Comment