Tuesday, June 14, 2011

Hosting a WCF Service in a Managed Application

WCF enables you to host your service through any managed application. This means you can use a Console application, a Windows service, a Windows Forms application, or even an application built with Windows Presentation Foundation.

Hosting a WCF Service by Using a Console Application

The Console application must specifically create and open an instance of the ServiceHost object. The ServiceHost then remains open and available until it is no longer needed.

• Create a New Project from the File menu and select WcfServiceLibrary.
Create and Implement service.
Build the project.
• Create ConsoleApplication named ConsoleServiceHost. From the project menu select Add Reference option and select the WcfServiceLibrary1.dll. Click ok.
Write the following code in the Main function.

ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
Console.WriteLine("Service Started...");
Console.WriteLine("\nPress any key to stop...");

Add an Application Configuration file to the project. And write the following configuration settings in the app.config.
<service name="WcfServiceLibrary1.Service1" behaviorConfiguration="WcfServiceLibrary1.Service1Behavior">
<add baseAddress = "http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
<endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<behavior name="WcfServiceLibrary1.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>

• Create a new console application. Copy the address from the app.config of ConsoleServiceHost application. Add service reference. Write the following code in the main function.
Console.WriteLine("Press ENTER when the service has started");

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

Console.WriteLine("Press any key to exit");

No comments: