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.
Eg:
• 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));
            host.Open();
            Console.WriteLine("Service Started...");
            Console.WriteLine("\nPress any key to stop...");
            Console.ReadLine();
      host.Close();
Add an Application Configuration file to the project. And write the following configuration settings in the app.config.<configuration>
  <system.serviceModel>
    <services>
      <service name="WcfServiceLibrary1.Service1" behaviorConfiguration="WcfServiceLibrary1.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
          </baseAddresses>
        </host>
        <endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfServiceLibrary1.Service1Behavior">
         <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
• 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");
            Console.Read();
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
            Console.WriteLine(client.GetData(33));
            client.Close();
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
      Console.ReadLine();
No comments:
Post a Comment